Exemplo n.º 1
0
 public static byte[] GetBytes(this Bitmap bitmap, OutputFormat outputFormat)
 {
     using (var memStream = new MemoryStream())
     {
         bitmap.MakeTransparent(BackgroundColour);
         switch (outputFormat)
         {
             case OutputFormat.Jpeg:
                 bitmap.Save(memStream, ImageFormat.Jpeg);
                 break;
             case OutputFormat.Gif:
                 bitmap.Save(memStream, ImageFormat.Gif);
                 break;
             case OutputFormat.Png:
                 bitmap.Save(memStream, ImageFormat.Png);
                 break;
             case OutputFormat.HighQualityJpeg:
                 var p = new EncoderParameters(1);
                 p.Param[0] = new EncoderParameter(Encoder.Quality, (long)95);
                 bitmap.Save(memStream, GetImageCodeInfo("image/jpeg"), p);
                 break;
         }
         return memStream.ToArray();
     }
 }
Exemplo n.º 2
0
 public static byte[] GetBytes(this Bitmap bitmap, OutputFormat outputFormat)
 {
     using (var memStream = (MemoryStream) bitmap.GetStream(outputFormat))
     {
         return memStream.ToArray();
     }
 }
Exemplo n.º 3
0
 public byte[] Get(string relativeFilePath, int width, int height, ImageMod imageMod, string hexBackgroundColour, AnchorPosition? anchor, OutputFormat outputFormat)
 {
     using (var bitmap = Get(relativeFilePath, width, height, imageMod, hexBackgroundColour, anchor))
     {
         return bitmap.GetBytes(outputFormat);
     }
 }
Exemplo n.º 4
0
        /// <summary>
        /// Formats number as requested by <paramref name="outputFormat"/>.
        /// </summary>
        /// <param name="number">Number to be formatted.</param>
        /// <param name="outputFormat">Format to be applied.</param>
        /// <exception cref="ArgumentNullException">Thrown when no number parameter is provided.</exception>
        /// <exception cref="ArgumentException">Thrown when invalid format parameted is provided.</exception>
        /// <returns>Formatted number as string.</returns>
        public static string FormatNumber(object number, OutputFormat outputFormat)
        {
            double parsedNumber;
            if (number != null && double.TryParse(number.ToString(), out parsedNumber))
            {
                if (Enum.IsDefined(typeof(OutputFormat), outputFormat))
                {
                    string result;
                    switch (outputFormat)
                    {
                        case OutputFormat.Float:
                            result = string.Format("{0:f2}", number);
                            break;
                        case OutputFormat.Percentage:
                            result = string.Format("{0:p0}", number);
                            break;
                        case OutputFormat.Normal:
                            result = string.Format("{0,8}", number);
                            break;
                        default:
                            throw new ArgumentException("Illegal format parameter provided!");
                    }

                    return result;
                }

                throw new ArgumentException("Invalid format argument provided!");
            }

            throw new ArgumentNullException("number", "No number provided to be formated!");
        }
Exemplo n.º 5
0
 public FlexWikiWebApplication(string configPath, LinkMaker linkMaker,
     OutputFormat outputFormat)
 {
     _configPath = configPath;
     _linkMaker = linkMaker;
     _outputFormat = outputFormat; 
 }
        public IValidatorReportItem ValidateUrl(string url, Stream output, OutputFormat outputFormat)
        {
            if (!IsValidUrl(url))
            {
                return ReportFailure(url, string.Empty, "The url is not in a valid format.");
            }

            var validatorUrl = mContext.ValidatorUrl;
            var input = url;
            var inputFormat = InputFormat.Uri;

            // wrap in try/catch so any error can be reported in the output
            try
            {
                if (mContext.DirectInputMode)
                {
                    // Retrieve the text from the webserver and input it directly
                    // to the W3C API
                    inputFormat = InputFormat.Fragment;
                    input = mHttpClient.GetResponseText(url);
                }

                var validatorResult = mValidator.Validate(output, outputFormat, input, inputFormat, mContext, validatorUrl);

                return ReportSuccess(
                    url,
                    GetDomainName(url),
                    validatorResult.Errors,
                    validatorResult.IsValid);
            }
            catch (Exception ex)
            {
                return ReportFailure(url, GetDomainName(url), ex.Message);
            }
        }
Exemplo n.º 7
0
 public ProcessingWindow(string[] pathsOfFilesToProcess, DestinationShape destinationShape, OutputFormat outputFormat)
 {
     InitializeComponent();
     _paths = pathsOfFilesToProcess;
     _destinationShape = destinationShape;
     _outputFormat = outputFormat;
 }
        /// <summary>
        /// Creates a new session for assembling documents using the HotDocs Cloud Services Rest API.
        /// </summary>
        /// <param name="template">The template to use with the session.</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="answers">The answers to use.</param>
        /// <param name="markedVariables">An array of variable names, whose prompts should be "marked" when displayed in an interview.</param>
        /// <param name="interviewFormat">The format to use when displaying an interview.</param>
        /// <param name="outputFormat">The format to use when assembling a document.</param>
        /// <param name="settings">The settings to use with the session.</param>
        /// <param name="theme">The interview theme.</param>
        /// <param name="showDownloadLinks">Indicates whether or not links for downloading the assembled document(s) should appear at the end of the interview.</param>
        /// <returns></returns>
        public string CreateSession(
			Template template,
			string billingRef = null,
			string answers = null,
			string[] markedVariables = null,
			InterviewFormat interviewFormat = InterviewFormat.JavaScript,
			OutputFormat outputFormat = OutputFormat.Native,
			Dictionary<string, string> settings = null,
			string theme = null,
			bool showDownloadLinks = true
		)
        {
            return (string)TryWithoutAndWithPackage(
                (uploadPackage) => CreateSessionImpl(
                    template,
                    billingRef,
                    answers,
                    markedVariables,
                    interviewFormat,
                    outputFormat,
                    settings,
                    theme,
                    showDownloadLinks,
                    uploadPackage)
            );
        }
Exemplo n.º 9
0
    private void GrabSingleView(EditorWindow view, FileInfo targetFile, OutputFormat format)
    {
        var width = Mathf.FloorToInt(view.position.width);
        var height = Mathf.FloorToInt(view.position.height);

        Texture2D screenShot = new Texture2D(width, height);

        this.HideOnGrabbing();

        var colorArray = InternalEditorUtility.ReadScreenPixel(view.position.position, width, height);

        screenShot.SetPixels(colorArray);

        byte[] encodedBytes = null;
        if (format == OutputFormat.jpg)
        {
            encodedBytes = screenShot.EncodeToJPG();
        }
        else
        {
            encodedBytes = screenShot.EncodeToPNG();
        }

        File.WriteAllBytes(targetFile.FullName, encodedBytes);

        this.ShowAfterHiding();
    }
Exemplo n.º 10
0
 public string Export(OutputFormat format = OutputFormat.Html)
 {
     using(StringWriter sw = new StringWriter())
     {
         Export(sw, format);
         return sw.ToString();
     }
 }
Exemplo n.º 11
0
        public MockWikiApplication(LinkMaker linkMaker,
            OutputFormat outputFormat)
        {
            _linkMaker = linkMaker;
            _ouputFormat = outputFormat;

            LoadConfiguration();
        }
Exemplo n.º 12
0
 public MockWikiApplication(FederationConfiguration configuration, LinkMaker linkMaker,
     OutputFormat outputFormat, ITimeProvider timeProvider)
 {
     _configuration = configuration;
     _linkMaker = linkMaker;
     _ouputFormat = outputFormat;
     _timeProvider = timeProvider;
 }
Exemplo n.º 13
0
        /// <summary>
        /// Returns SHA1 Digest of UTF8 representation of input string
        /// </summary>
        /// <param name="source">String that will use UTF8 encoding</param>
        /// <param name="outputFormat">Formatting to be applied to output string.</param>
        /// <returns>SHA1 digest in format specified by <paramref name="outputFormat"/></returns>
        /// <exception cref="ValidationException">Thrown if <paramref name="source"/> is null or empty</exception>
        public static string SHA1Hash(this string source, OutputFormat outputFormat = OutputFormat.Hex)
        {
            Validate.Begin()
                .IsNotNull(source, "source")
                .IsNotEmpty(source, "source")
                .CheckForExceptions();

            return SHA1HashImplementation(source, outputFormat);
        }
Exemplo n.º 14
0
        public Stream Generate(string dotSource, LayoutEngine engine, OutputFormat fmt)
        {
            var res = processRunner.Run(dotExe, new MemoryStream(Encoding.ASCII.GetBytes(dotSource)), engine.AsCmdLineParam(), fmt.AsCmdLineParam());
            if (res.ExitCode!=0)
                throw new Exception(
                    string.Format("Process [{4}] finished with non-zero code:[{0}] \nwhile generating data format: [{1}] using layout engine: [{2}]\nsrc={3}",
                        res.ExitCode, fmt, engine, dotSource.Shorter(), dotExe));

            return res.StdOut;
        }
Exemplo n.º 15
0
 public void Write(OutputFormat format, string text, params object[] args)
 {
     var str =
         format == OutputFormat.Error ? "<!e!>" + text + "</!e!>" :
         format == OutputFormat.Important ? "<!i!>" + text + "</!i!>" :
         format == OutputFormat.Header ? "<!h!>" + text + "</!h!>" :
         format == OutputFormat.Warning ? "<!w!>" + text + "</!w!>" :
         text;
     View().WriteString(str, args);
 }
Exemplo n.º 16
0
        /// <summary>
        ///   Creates an image media.
        /// </summary>
        /// <param name = "parentId">The parent media id.</param>
        /// <param name = "mediaName">Name of the media.</param>
        /// <param name = "image">The image.</param>
        /// <param name = "outputFormat">The output format.</param>
        /// <returns>Media Url</returns>
        public static int CreateImageMedia(int parentId, string mediaName, Image image, OutputFormat outputFormat)
        {
            // Create media item
            mediaName = LegalizeString(mediaName.Replace(" ", "-"));
            var mediaItem = Media.MakeNew(mediaName, MediaType.GetByAlias("image"), new User(0), parentId);

            // Filename
            // i.e. 1234.jpg
            var mediaFileName = string.Format("{0}.{1}", mediaItem.Id, outputFormat);
            var mediaThumbName = string.Format("{0}_thumb.{1}", mediaItem.Id, outputFormat);

            // Client side Paths
            //
            //      sample folder : /media/1234/
            //                    : /media/1234/1234.jpg
            //
            var clientMediaFolder = string.Format("{0}/../media/{1}", GlobalSettings.Path, mediaItem.Id);
            var clientMediaFile = string.Format("{0}/{1}", clientMediaFolder, mediaFileName);
            var clientMediaThumb = string.Format("{0}/{1}", clientMediaFolder, mediaThumbName);

            // Server side Paths
            var serverMediaFolder = IOHelper.MapPath(clientMediaFolder);
            var serverMediaFile = IOHelper.MapPath(clientMediaFile);
            var serverMediaThumb = IOHelper.MapPath(clientMediaThumb);

            var extension = Path.GetExtension(serverMediaFile).ToLower();

            // Create media folder if it doesn't exist
            if (!Directory.Exists(serverMediaFolder))
                Directory.CreateDirectory(serverMediaFolder);

            // Save Image and thumb for new media item
            image.Save(serverMediaFile);
            var savedImage = Image.FromFile(serverMediaFile);
            savedImage.GetThumbnailImage((int) (image.Size.Width*.3), (int) (image.Size.Height*.3), null, new IntPtr()).
                Save(serverMediaThumb);

            mediaItem.getProperty(Constants.Umbraco.Media.Width).Value = savedImage.Size.Width.ToString();
            mediaItem.getProperty(Constants.Umbraco.Media.Height).Value = savedImage.Size.Height.ToString();
            mediaItem.getProperty(Constants.Umbraco.Media.File).Value = clientMediaFile;
            mediaItem.getProperty(Constants.Umbraco.Media.Extension).Value = extension;
            mediaItem.getProperty(Constants.Umbraco.Media.Bytes).Value = File.Exists(serverMediaFile)
                                                              ? new FileInfo(serverMediaFile).Length.ToString()
                                                              : "0";

            mediaItem.Save();
            mediaItem.XmlGenerate(new XmlDocument());

            image.Dispose();
            savedImage.Dispose();

            // assign output parameters
            return mediaItem.Id;
        }
Exemplo n.º 17
0
		/// <summary>
		/// Answer the formatted text for a given topic, formatted using a given OutputFormat and possibly showing diffs with the previous revision
		/// </summary>
		/// <param name="topic">The topic</param>
		/// <param name="format">What format</param>
		/// <param name="showDiffs">true to show diffs</param>
		/// <param name="accumulator">composite cache rule in which to accumulate cache rules</param>
		/// <returns></returns>
		public static string FormattedTopic(AbsoluteTopicName topic, OutputFormat format, bool showDiffs, Federation aFederation, LinkMaker lm, CompositeCacheRule accumulator)
		{ 
		
			// Show the current topic (including diffs if there is a previous version)
			AbsoluteTopicName previousVersion = null;
			ContentBase relativeToBase = aFederation.ContentBaseForNamespace(topic.Namespace);

			if (showDiffs)
				previousVersion = relativeToBase.VersionPreviousTo(topic.LocalName);

			return FormattedTopicWithSpecificDiffs(topic, format, previousVersion, aFederation, lm, accumulator);
		}
Exemplo n.º 18
0
 public void Export(TextWriter writer, OutputFormat format = OutputFormat.Html)
 {
     IDocumentVisitor visitor = null;
     switch (format)
     {
         case OutputFormat.Html: visitor = new HtmlPrinter(writer); break;
         case OutputFormat.SyntaxTree: visitor = new AstPrinter(writer); break;
         case OutputFormat.CommonMark: visitor = new CommonMarkPrinter(writer); break;
     }
     Accept(visitor);
     if (visitor is IDisposable)
         ((IDisposable)visitor).Dispose();
 }
Exemplo n.º 19
0
		public SpellResult CheckText(string text, Lang[] lang = null, SpellerOptions? options = null, OutputFormat? format = null)
		{
			RestRequest request = new RestRequest("checkText");
			request.AddParameter("text", text);
			if (lang != null && lang.Length != 0)
				request.AddParameter("lang", string.Join(",", lang.Select(l => l.ToString().ToLowerInvariant())));
			if (options.HasValue)
				request.AddParameter("options", (int)options.Value);
			if (format.HasValue)
				request.AddParameter("format", format.Value.ToString().ToLowerInvariant());

			return SendRequest<SpellResult>(request);
		}
Exemplo n.º 20
0
		/// <summary>
		/// Format a string of wiki content in a given OutputFormat with references all being relative to a given namespace
		/// </summary>
		/// <param name="input">The input wiki text</param>
		/// <param name="format">The desired output format</param>
		/// <param name="relativeToContentBase">References will be relative to this namespace</param>
		/// <param name="lm">Link maker (unless no relativeTo content base is provide)</param>
		/// <param name="accumulator">composite cache rule in which to accumulate cache rules</param>
		/// <returns></returns>
		public static string FormattedString(string input, OutputFormat format, ContentBase relativeToContentBase, LinkMaker lm, CompositeCacheRule accumulator)
		{
			// TODO -- some of the cases in which this call happens actually *are* nested, even though the false arg
			// below says that they aren't.  This causes scripts to be emitted multiple times -- should clean up.
			WikiOutput output = WikiOutput.ForFormat(format, null);	
			Hashtable ew;
			if (relativeToContentBase != null)
				ew = relativeToContentBase.ExternalWikiHash();
			else
				ew = new Hashtable();
			Format(null, input, output, relativeToContentBase, lm, ew, 0, accumulator);
			return output.ToString();
		}
Exemplo n.º 21
0
 public static string GetOutput(this Table table, OutputFormat format, int tableWidth = 77, string separator = ",")
 {
     switch (format)
     {
         case OutputFormat.Table:
             return GetTextOutput(table, tableWidth);
         case OutputFormat.HTML:
             return GetHTLMOutput(table, tableWidth);
         case OutputFormat.DataList:
             return GetDataListOutput(table, separator);
         default:
             throw new ArgumentOutOfRangeException("format");
     }
 }
Exemplo n.º 22
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="rest"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        /// <exception cref="">InvalidSystemException</exception>
        public static string Parse(string rest, OutputFormat format)
        {
            TextReader reader = new StringReader(rest);
            System system;
            bool success = System.Parse(reader, out system);

            if (!success)
                throw new InvalidSystemException("Could not parse as a system");

            if (reader.Peek() != -1)
                throw new InvalidSystemException(String.Format("Saw unexpected character: {0}", (char)reader.Read()));

            return system.ToString(format);
        }
Exemplo n.º 23
0
    public static WikiOutput ForFormat(OutputFormat aFormat, WikiOutput parent)
    {
      switch (aFormat)
      {
        case OutputFormat.HTML:
          return new HTMLWikiOutput(parent);

        case OutputFormat.Testing:
          return new TestWikiOutput(parent);

        default:
          throw new Exception("Unsupported output type requested: " + aFormat.ToString());
      }
    }
Exemplo n.º 24
0
 public static string GetContentType(OutputFormat outputFormat)
 {
     switch (outputFormat)
     {
         case OutputFormat.Gif:
             return "image/gif";
         case OutputFormat.Png:
             return "image/png";
         case OutputFormat.Jpeg:
         case OutputFormat.HighQualityJpeg:
             return "image/jpeg";
         default:
             return null;
     }
 }
Exemplo n.º 25
0
        public static string FileNameFor(string language, OutputFormat outputFormat)
        {
            if (outputFormat == OutputFormat.AndroidXml)
            {
                var folderName = (language == "en" ? "values" : String.Concat("values-", language));
                return Path.Combine("Resources", folderName, "Strings.xml");
            }

            if (outputFormat == OutputFormat.PList || outputFormat == OutputFormat.Strings)
                return Path.Combine(language + ".lproj", "Localizable.strings");

            if (outputFormat == OutputFormat.ResX)
                return String.Concat("AppResources.", language, ".resx");

            return String.Concat(language, ".xml");
        }
Exemplo n.º 26
0
        private static string SHA1HashImplementation(string source, OutputFormat outputFormat)
        {
            Debug.Assert(source != null, "source != null");
            Debug.Assert(source.Length > 0);

            byte[] bytes;
            using (SHA1 sha = new SHA1Managed())
            {
                bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(source));
            }

            if (outputFormat == OutputFormat.Hex)
            {
                return bytes.ToHexString();
            }

            return outputFormat == OutputFormat.Base64 ? Convert.ToBase64String(bytes) : bytes.Select(x => string.Format("{0:d3}", x)).FlattenStrings();
        }
Exemplo n.º 27
0
        public void Write(IEnumerable<BigInteger> results)
        {
            try
            {
                var resultsObject = new OutputFormat { Result = results.Select(x => x.ToString("R0")).ToArray() };

                using (var fileStream = new FileStream(_path, FileMode.Create))
                using (var xmlWriter = new XmlTextWriter(fileStream, Encoding.Unicode))
                {
                    var serializer = new XmlSerializer(typeof(OutputFormat));
                    serializer.Serialize(xmlWriter, resultsObject);
                }
            }
            catch (IOException ex)
            {
                throw new ApplicationException("There was a problem writing the xml file to disk", ex);
            }
        }
Exemplo n.º 28
0
		public Translation Translate(string text, LangPair lang, OutputFormat? format = null, bool options = false)
		{
			RestRequest request = new RestRequest("translate");
			request.AddParameter("key", _key);
			request.AddParameter("text", text);
			if (lang.OutputLang != Lang.None)
			{
				if (lang.InputLang == Lang.None)
					request.AddParameter("lang", lang.OutputLang.ToString().ToLowerInvariant());
				else
					request.AddParameter("lang", lang.ToString().ToLowerInvariant());
			}
			if (format.HasValue)
				request.AddParameter("format", format.ToString().ToLowerInvariant());
			if (options)
				request.AddParameter("options", "1");

			return SendRequest<Translation>(request);
		}
Exemplo n.º 29
0
 /// <summary>
 ///   Initializes a new instance of the <see cref = "TextImageParameters" /> class.
 /// </summary>
 /// <param name = "textString">The node property.</param>
 /// <param name = "outputFormat">The output format.</param>
 /// <param name = "customFontPath">The custom font path.</param>
 /// <param name = "fontName">Name of the font.</param>
 /// <param name = "fontSize">Size of the font.</param>
 /// <param name = "fontStyles">The font style.</param>
 /// <param name = "foreColor">Color of the fore.</param>
 /// <param name = "backColor">Color of the back.</param>
 /// <param name = "shadowColor">Color of the shadow.</param>
 /// <param name = "hAlign">The h align.</param>
 /// <param name = "vAlign">The v align.</param>
 /// <param name = "canvasHeight">Height of the canvas.</param>
 /// <param name = "canvasWidth">Width of the canvas.</param>
 /// <param name = "backgroundMedia">The background image.</param>
 public TextImageParameters(string textString, OutputFormat outputFormat, string customFontPath, string fontName,
                            int fontSize, FontStyle[] fontStyles, string foreColor, string backColor,
                            string shadowColor, HorizontalAlignment hAlign, VerticalAlignment vAlign,
                            int canvasHeight, int canvasWidth, Media backgroundMedia)
 {
     _text = textString;
     _outputFormat = outputFormat;
     _customFontPath = customFontPath;
     _fontName = fontName;
     _fontSize = fontSize;
     _fontStyles = fontStyles;
     _foreColor = foreColor;
     _backColor = backColor;
     _hAlign = hAlign;
     _vAlign = vAlign;
     _canvasHeight = canvasHeight;
     _canvasWidth = canvasWidth;
     _shadowColor = shadowColor;
     _backgroundMedia = backgroundMedia;
 }
Exemplo n.º 30
0
        public FlexWikiWebApplication(string configPath, LinkMaker linkMaker,
            OutputFormat outputFormat)
        {
            _configPath = configPath;
            _linkMaker = linkMaker;
            _outputFormat = outputFormat;

            LoadConfiguration();
            // We no longer watch the config file for changes because it was causing too
            // many problems. Now there's just a "reload configuration" button in
            // the admin app (not yet implemented).
            //WatchConfiguration();

            string log4NetConfigPath = "log4net.config";
            if (_applicationConfiguration.Log4NetConfigPath != null)
            {
                log4NetConfigPath = _applicationConfiguration.Log4NetConfigPath;
            }
            XmlConfigurator.ConfigureAndWatch(new FileInfo(ResolveRelativePath(log4NetConfigPath)));
        }
        public QueryResult <OutputFilenameResult> GetFileName(string directory, string filename, OutputFormat outputFormat)
        {
            var interaction = CreateFileNameInteraction(filename, directory, outputFormat);
            var result      = InvokeInteraction(interaction, outputFormat, true);

            return(result);
        }
        private SaveFileInteraction CreateFileNameInteraction(string fileName, string directory, OutputFormat outputFormat)
        {
            if (!string.IsNullOrWhiteSpace(directory))
            {
                var success = CreateTargetDirectory(directory);

                if (!success)
                {
                    _logger.Warn("Could not create directory for save file dialog. It will be opened with default save location.");
                    directory = "";
                }
            }

            var interaction = new SaveFileInteraction();

            interaction.Title            = _translation.SelectDestination;
            interaction.Filter           = GetAllFilters();
            interaction.FilterIndex      = (int)outputFormat + 1;
            interaction.OverwritePrompt  = true;
            interaction.ForceTopMost     = true;
            interaction.FileName         = fileName;
            interaction.InitialDirectory = directory;

            return(interaction);
        }
Exemplo n.º 33
0
        /// <summary>
        /// Generates the chosen document from the input parameters.
        /// </summary>
        /// <param name="xml">Xml containing data.</param>
        /// <param name="xslt">XSL Transformation.</param>
        /// <param name="printProfileXml">Print profile XML.</param>
        /// <param name="driverConfigXml">Driver config XML.</param>
        /// <param name="format">Output format.</param>
        /// <param name="output">Output stream.</param>
        public static void Generate(string xml, string xslt, string printProfileXml, string driverConfigXml, OutputFormat format, Stream output)
        {
            string inputXml = MakoPrintPdf.TransformXml(xml, xslt, printProfileXml, driverConfigXml);

            switch (format)
            {
            case OutputFormat.Html:
            case OutputFormat.Xml:
                StreamWriter writer = new StreamWriter(output);
                writer.Write(inputXml);
                writer.Flush();
                break;

            case OutputFormat.Csv:
                MakoPrintCsv.Generate(inputXml, output);
                break;

            case OutputFormat.Fiscal:
                MakoPrintFiscal.Generate(inputXml, output);
                break;

            case OutputFormat.Pdf:
                MakoPrintPdf.GeneratePdf(inputXml, output);
                break;

            case OutputFormat.Xls:
                MakoPrintXls.Generate(inputXml, output);
                break;

            case OutputFormat.Vcf:
                MakoPrintVCard.Generate(inputXml, output);
                break;

            case OutputFormat.Text:
                MakoPrintText.Generate(inputXml, output, driverConfigXml);
                break;
            }
        }
Exemplo n.º 34
0
        private string CreateSessionImpl(
            Template template,
            string billingRef,
            string answers,
            string[] markedVariables,
            InterviewFormat interviewFormat,
            OutputFormat outputFormat,
            Dictionary <string, string> settings,
            string theme,
            bool showDownloadLinks,
            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 hmac = HMAC.CalculateHMAC(
                SigningKey,
                timestamp,
                SubscriberId,
                packageTemplateLocation.PackageID,
                billingRef,
                interviewFormat,
                outputFormat,
                settings);                 // Additional settings = null for this app

            StringBuilder urlBuilder = new StringBuilder(string.Format(
                                                             "{0}/newsession/{1}/{2}?interviewformat={3}&outputformat={4}",
                                                             EmbeddedEndpointAddress, SubscriberId, packageTemplateLocation.PackageID,
                                                             interviewFormat.ToString(), outputFormat.ToString()));

            if (markedVariables != null && markedVariables.Length > 0)
            {
                urlBuilder.AppendFormat("&markedvariables={0}", string.Join(",", markedVariables));
            }

            if (!string.IsNullOrEmpty(theme))
            {
                urlBuilder.AppendFormat("&theme={0}", theme);
            }

            if (!string.IsNullOrEmpty(billingRef))
            {
                urlBuilder.AppendFormat("&billingref={0}", billingRef);
            }

            if (showDownloadLinks)
            {
                urlBuilder.Append("&showdownloadlinks=true");
            }

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

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

            request.Method               = "POST";
            request.ContentType          = "text/xml; charset=utf-8";
            request.Headers["x-hd-date"] = timestamp.ToString("r");
            request.Headers[HttpRequestHeader.Authorization] = hmac;
            byte[] data = null;
            if (answers != null)
            {
                data = Encoding.UTF8.GetBytes(answers);
            }
            request.ContentLength = data != null ? data.Length : 0;

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

            Stream stream = request.GetRequestStream();

            if (data != null)
            {
                stream.Write(data, 0, data.Length);
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader    reader   = new StreamReader(response.GetResponseStream());

            return(reader.ReadLine());
        }
Exemplo n.º 35
0
 public Delegate Compile(Type modelType, String template, OutputFormat outputFormat)
 {
     return(CompileInternal(modelType, template, outputFormat));
 }
Exemplo n.º 36
0
 public Func <TModel, IFormatProvider, String> Compile <TModel>(String template, OutputFormat outputFormat)
 {
     return((Func <TModel, IFormatProvider, String>)CompileInternal(typeof(TModel), template, outputFormat));
 }
Exemplo n.º 37
0
 public GraphTraversal2(GraphViewConnection pConnection)
 {
     this.connection   = pConnection;
     this.outputFormat = OutputFormat.Regular;
 }
Exemplo n.º 38
0
        public void ReadArguments(string[] parameters)
        {
            if (parameters.Length == 0)
            {
                throw new Exception("No parameter is specified!");
            }

            #region Assigning crexport parameters to variables
            for (int i = 0; i < parameters.Count(); i++)
            {
                if (i + 1 < parameters.Count())
                {
                    if (parameters[i + 1].Length > 0)
                    {
                        if (parameters[i].ToUpper() == "-U")
                        {
                            UserName = parameters[i + 1];
                        }
                        else if (parameters[i].ToUpper() == "-P")
                        {
                            Password = parameters[i + 1];
                        }
                        else if (parameters[i].ToUpper() == "-F")
                        {
                            ReportPath = parameters[i + 1];
                        }
                        else if (parameters[i].ToUpper() == "-O")
                        {
                            OutputPath = parameters[i + 1];
                        }
                        else if (parameters[i].ToUpper() == "-S")
                        {
                            ServerName = parameters[i + 1];
                        }
                        else if (parameters[i].ToUpper() == "-D")
                        {
                            DatabaseName = parameters[i + 1];
                        }
                        else if (parameters[i].ToUpper() == "-E")
                        {
                            OutputFormat = parameters[i + 1];
                            if (OutputFormat.Equals("print", StringComparison.OrdinalIgnoreCase))
                            {
                                PrintOutput = true;
                            }
                        }
                        else if (parameters[i].ToUpper() == "-N")
                        {
                            PrinterName = parameters[i + 1];
                        }
                        else if (parameters[i].ToUpper() == "-C")
                        {
                            try
                            {
                                PrintCopy = Convert.ToInt32(parameters[i + 1]);
                            }
                            catch (Exception ex)
                            { throw ex; }
                        }
                        else if (parameters[i].ToUpper() == "-A")
                        {
                            ParameterCollection.Add(parameters[i + 1]);
                        }
                        else if (parameters[i].ToUpper() == "-TO")
                        {
                            MailTo = parameters[i + 1];
                        }
                        else if (parameters[i].ToUpper() == "-LC")
                        {
                            LCID = int.Parse(parameters[i + 1]);
                        }
                    }
                }

                if (parameters[i] == "-?" || parameters[i] == "/?")
                {
                    GetHelp = true;
                }

                if (parameters[i].ToUpper() == "-L")
                {
                    EnableLog = true;
                }

                if (parameters[i].ToUpper() == "-NR")
                {
                    Refresh = false;
                }
            }
            #endregion
        }
        private static void PublishOutput(List <DataModel> dataCollection, OutputFormat format)
        {
            IFileOutput myFormat = FileOutputFactory.GetMyFormatter(format);

            myFormat.GenerateOutput(dataCollection, "");
        }
Exemplo n.º 40
0
        private string GetGameType(OutputFormat outputFormat)
        {
            var gameType = _replay.GameType;

            return(outputFormat == OutputFormat.Short ? GetShortFormGameType(gameType) : gameType.ToString());
        }
Exemplo n.º 41
0
        private RepositoryUpdatesFormatted FormatRepositoryUpdates(RepositoryUpdates repoUpdates, OutputFormat outputFormat)
        {
            switch (outputFormat)
            {
            case OutputFormat.space_delimited:
                return(new RepositoryUpdatesFormatted
                {
                    FilesAddedFormatted = string.Join(' ', repoUpdates.FilesAdded),
                    FilesModifiedFormatted = string.Join(' ', repoUpdates.FilesModified),
                    FilesAddedModifiedFormatted = string.Join(' ', repoUpdates.FilesAddedModified),
                    FilesRemovedFormatted = string.Join(' ', repoUpdates.FilesRemoved),
                    FilesRenamedFormatted = string.Join(' ', repoUpdates.FilesRenamed),
                    FilesAllFormatted = string.Join(' ', repoUpdates.FilesAll)
                });

            case OutputFormat.csv:
                return(new RepositoryUpdatesFormatted
                {
                    FilesAddedFormatted = string.Join(',', repoUpdates.FilesAdded),
                    FilesModifiedFormatted = string.Join(',', repoUpdates.FilesModified),
                    FilesAddedModifiedFormatted = string.Join(',', repoUpdates.FilesAddedModified),
                    FilesRemovedFormatted = string.Join(',', repoUpdates.FilesRemoved),
                    FilesRenamedFormatted = string.Join(',', repoUpdates.FilesRenamed),
                    FilesAllFormatted = string.Join(',', repoUpdates.FilesAll)
                });

            case OutputFormat.json:
                return(new RepositoryUpdatesFormatted
                {
                    FilesAddedFormatted = JsonConvert.SerializeObject(repoUpdates.FilesAdded),
                    FilesModifiedFormatted = JsonConvert.SerializeObject(repoUpdates.FilesModified),
                    FilesAddedModifiedFormatted = JsonConvert.SerializeObject(repoUpdates.FilesAddedModified),
                    FilesRemovedFormatted = JsonConvert.SerializeObject(repoUpdates.FilesRemoved),
                    FilesRenamedFormatted = JsonConvert.SerializeObject(repoUpdates.FilesRenamed),
                    FilesAllFormatted = JsonConvert.SerializeObject(repoUpdates.FilesAll)
                });

            default:
                throw new Exception("Invalid output format");
            }
        }
Exemplo n.º 42
0
        async Task <RepositoryUpdatesFormatted> IModelValidationService.GetRepositoryUpdates(long repoId, int pullRequestId, OutputFormat outputFormat)
        {
            IEnumerable <PullRequestFile> allFiles = await gitClient.PullRequest.Files(repoId, pullRequestId);

            var repoUpdates = new RepositoryUpdates
            {
                FilesAdded         = new List <string>(),
                FilesModified      = new List <string>(),
                FilesRemoved       = new List <string>(),
                FilesRenamed       = new List <string>(),
                FilesAddedModified = new List <string>(),
                FilesAll           = new List <string>()
            };

            foreach (PullRequestFile file in allFiles)
            {
                if (outputFormat == OutputFormat.space_delimited && file.FileName.Contains(" "))
                {
                    throw new Exception("One of your files includes a space. Consider using a different output format or removing spaces from your filenames. Please submit an issue on this action's GitHub repo.");
                }

                repoUpdates.FilesAll.Add(file.FileName);

                FileChangeStatus fileStatus = (FileChangeStatus)System.Enum.Parse(typeof(FileChangeStatus), file.Status);

                switch (fileStatus)
                {
                case FileChangeStatus.added:
                    repoUpdates.FilesAdded.Add(file.FileName);
                    repoUpdates.FilesAddedModified.Add(file.FileName);
                    break;

                case FileChangeStatus.modified:
                    repoUpdates.FilesModified.Add(file.FileName);
                    repoUpdates.FilesAddedModified.Add(file.FileName);
                    break;

                case FileChangeStatus.removed:
                    repoUpdates.FilesRemoved.Add(file.FileName);
                    break;

                case FileChangeStatus.renamed:
                    repoUpdates.FilesRenamed.Add(file.FileName);
                    break;

                case FileChangeStatus.none:
                    continue;

                default:
                    throw new Exception("Invalid file status");
                }
            }

            var formattedRepoUpdates = FormatRepositoryUpdates(repoUpdates, outputFormat);

            return(formattedRepoUpdates);
        }
Exemplo n.º 43
0
 /// <summary>
 /// Performs tesseract OCR using wrapper for Tesseract OCR API for the selected page
 /// of input image (by default 1st).
 /// </summary>
 /// <remarks>
 /// Performs tesseract OCR using wrapper for Tesseract OCR API for the selected page
 /// of input image (by default 1st).
 /// Please note that list of output files is accepted instead of a single file because
 /// page number parameter is not respected in case of TIFF images not requiring preprocessing.
 /// In other words, if the passed image is the TIFF image and according to the
 /// <see cref="Tesseract4OcrEngineProperties"/>
 /// no preprocessing is needed, each page of the TIFF image is OCRed and the number of output files in the list
 /// is expected to be same as number of pages in the image, otherwise, only one file is expected
 /// </remarks>
 /// <param name="inputImage">
 /// input image
 /// <see cref="System.IO.FileInfo"/>
 /// </param>
 /// <param name="outputFiles">
 ///
 /// <see cref="System.Collections.IList{E}"/>
 /// of output files
 /// (one per each page)
 /// </param>
 /// <param name="outputFormat">
 /// selected
 /// <see cref="OutputFormat"/>
 /// for tesseract
 /// </param>
 /// <param name="pageNumber">number of page to be processed</param>
 internal override void DoTesseractOcr(FileInfo inputImage, IList <FileInfo> outputFiles, OutputFormat outputFormat
                                       , int pageNumber)
 {
     ScheduledCheck();
     try {
         ValidateLanguages(GetTesseract4OcrEngineProperties().GetLanguages());
         InitializeTesseract(outputFormat);
         OnEvent();
         // if preprocessing is not needed and provided image is tiff,
         // the image will be paginated and separate pages will be OCRed
         IList <String> resultList = new List <String>();
         if (!GetTesseract4OcrEngineProperties().IsPreprocessingImages() && ImagePreprocessingUtil.IsTiffImage(inputImage
                                                                                                               ))
         {
             resultList = GetOcrResultForMultiPage(inputImage, outputFormat);
         }
         else
         {
             resultList.Add(GetOcrResultForSinglePage(inputImage, outputFormat, pageNumber));
         }
         // list of result strings is written to separate files
         // (one for each page)
         for (int i = 0; i < resultList.Count; i++)
         {
             String   result     = resultList[i];
             FileInfo outputFile = i >= outputFiles.Count ? null : outputFiles[i];
             if (result != null && outputFile != null)
             {
                 try {
                     using (TextWriter writer = new StreamWriter(new FileStream(outputFile.FullName, FileMode.Create), System.Text.Encoding
                                                                 .UTF8)) {
                         writer.Write(result);
                     }
                 }
                 catch (System.IO.IOException e) {
                     LogManager.GetLogger(GetType()).Error(MessageFormatUtil.Format(Tesseract4LogMessageConstant.CANNOT_WRITE_TO_FILE
                                                                                    , e.Message));
                     throw new Tesseract4OcrException(Tesseract4OcrException.TESSERACT_FAILED);
                 }
             }
         }
     }
     catch (Tesseract4OcrException e) {
         LogManager.GetLogger(GetType()).Error(e.Message);
         throw new Tesseract4OcrException(e.Message, e);
     }
     finally {
         if (tesseractInstance != null)
         {
             TesseractOcrUtil.DisposeTesseractInstance(tesseractInstance);
         }
         if (GetTesseract4OcrEngineProperties().GetPathToUserWordsFile() != null && GetTesseract4OcrEngineProperties
                 ().IsUserWordsFileTemporary())
         {
             TesseractHelper.DeleteFile(GetTesseract4OcrEngineProperties().GetPathToUserWordsFile());
         }
     }
 }
Exemplo n.º 44
0
 public void SetContainer(OutputFormat container)
 {
     this.SelectedOutputFormat = container;
 }
Exemplo n.º 45
0
 private void SetOutputFormatExecute(OutputFormat parameter)
 {
     OutputFormat = parameter;
 }
        private QueryResult <OutputFilenameResult> InvokeInteraction(SaveFileInteraction interaction, OutputFormat outputFormat, bool canChangeFormat)
        {
            var result = new QueryResult <OutputFilenameResult> {
                Success = false
            };

            _interactionInvoker.Invoke(interaction);

            if (!interaction.Success)
            {
                return(result);
            }

            if (canChangeFormat)
            {
                outputFormat = (OutputFormat)interaction.FilterIndex - 1;
            }

            var outputFile         = interaction.FileName;
            var outputFormatHelper = new OutputFormatHelper();

            if (!outputFormatHelper.HasValidExtension(outputFile, outputFormat))
            {
                outputFile = outputFormatHelper.EnsureValidExtension(outputFile, outputFormat);
            }

            result.Success = true;
            result.Data    = new OutputFilenameResult(outputFile, outputFormat);
            return(result);
        }
Exemplo n.º 47
0
        public Arguments(string[] args)
        {
            if (args.Length >= 1)
            {
                Source = args[0];
            }

            for (int i = 1; i < args.Length; i++)
            {
                string undefinedArg = null;
                try
                {
                    switch (args[i].ToLower())
                    {
                    case "-c":
                    case "--credentials":
                        i++;
                        CredentialsFile = args[i];
                        break;

                    case "-o":
                    case "--output":
                        i++;
                        OutputFormat = args[i];
                        break;

                    case "-f":
                    case "--file":
                        i++;
                        OutputFile = args[i];
                        break;

                    case "-s":
                    case "--sql":
                        i++;
                        SqlConnectionString = args[i];
                        break;

                    case "-t":
                    case "--table":
                        i++;
                        TableName = args[i];
                        break;

                    case "-a":
                    case "--action":
                        i++;
                        SqlAction = args[i];
                        break;

                    case "-w":
                    case "--window":
                        OutputToWindow = true;
                        break;

                    default:
                        undefinedArg = args[i];
                        break;
                    }
                    if (undefinedArg != null)
                    {
                        if (i == 1)
                        {
                            QueryName = args[i];
                        }
                        else
                        {
                            throw new Exception($"Undefined argument: {args[i]}");
                        }
                    }
                }
                catch (IndexOutOfRangeException)
                {
                    throw new Exception($"Missing parameter for {args[i]}");
                }
            }

            if (!File.Exists(Source) && !Directory.Exists(Source))
            {
                throw new Exception($"Source not found: {Source}");
            }

            if (File.Exists(Source))
            {
                SourceFileExtension = Path.GetExtension(Source);
            }

            //OutputFlags = ExecuteOutputFlags.DataTable;
            if (!string.IsNullOrWhiteSpace(OutputFormat) ||
                !string.IsNullOrWhiteSpace(OutputFile)
                )
            {
                if (string.IsNullOrWhiteSpace(OutputFormat))
                {
                    string outputFileExtension = Path.GetExtension(OutputFile);
                    OutputFormat = outputFileExtension.Substring(1);
                }

                switch (OutputFormat.ToLower())
                {
                case "csv":
                    OutputFlags = ExecuteOutputFlags.Csv;
                    break;

                case "json":
                    OutputFlags = ExecuteOutputFlags.Json;
                    break;

                case "html":
                    OutputFlags = ExecuteOutputFlags.Html;
                    break;

                case "xml":
                    OutputFlags = ExecuteOutputFlags.Xml;
                    break;

                default:
                    throw new Exception($"Unsupported output format: {OutputFormat}");
                }
            }

            if (!string.IsNullOrWhiteSpace(SqlConnectionString))
            {
                switch (SqlAction.ToLower())
                {
                case "":
                    SqlTableAction = SqlTableAction.Create;
                    break;

                case "c":
                    SqlTableAction = SqlTableAction.Create;
                    break;

                case "dc":
                    SqlTableAction = SqlTableAction.DropAndCreate;
                    break;

                case "di":
                    SqlTableAction = SqlTableAction.DeleteAndInsert;
                    break;

                case "i":
                    SqlTableAction = SqlTableAction.Insert;
                    break;

                case "ti":
                    SqlTableAction = SqlTableAction.TruncateAndInsert;
                    break;

                default:
                    throw new Exception($"Unsupported action: {SqlAction}");
                }

                if (OutputFlags == null)
                {
                    OutputFlags = ExecuteOutputFlags.Sql;
                }
                else
                {
                    OutputFlags |= ExecuteOutputFlags.Sql;
                }
            }

            if (OutputFlags == null)
            {
                OutputFlags    = ExecuteOutputFlags.DataTable;
                OutputToWindow = true;
            }

            if (string.IsNullOrWhiteSpace(QueryName) && SourceFileExtension == ".pq")
            {
                QueryName = Path.GetFileNameWithoutExtension(Source);
            }

            if (string.IsNullOrWhiteSpace(QueryName))
            {
                throw new Exception($"Query name must be defined.");
            }

            if (string.IsNullOrWhiteSpace(TableName))
            {
                TableName = QueryName;
            }
        }
Exemplo n.º 48
0
        public override bool Execute()
        {
            try
            {
                Console.WriteLine("\nCalculating coverage result...");

                IFileSystem fileSystem = ServiceProvider.GetService <IFileSystem>();
                if (InstrumenterState is null || !fileSystem.Exists(InstrumenterState.ItemSpec))
                {
                    _logger.LogError("Result of instrumentation task not found");
                    return(false);
                }

                Coverage coverage = null;
                using (Stream instrumenterStateStream = fileSystem.NewFileStream(InstrumenterState.ItemSpec, FileMode.Open))
                {
                    IInstrumentationHelper instrumentationHelper = ServiceProvider.GetService <IInstrumentationHelper>();
                    // Task.Log is teared down after a task and thus the new MSBuildLogger must be passed to the InstrumentationHelper
                    // https://github.com/microsoft/msbuild/issues/5153
                    instrumentationHelper.SetLogger(_logger);
                    coverage = new Coverage(CoveragePrepareResult.Deserialize(instrumenterStateStream), _logger, ServiceProvider.GetService <IInstrumentationHelper>(), fileSystem, ServiceProvider.GetService <ISourceRootTranslator>());
                }

                try
                {
                    fileSystem.Delete(InstrumenterState.ItemSpec);
                }
                catch (Exception ex)
                {
                    // We don't want to block coverage for I/O errors
                    _logger.LogWarning($"Exception during instrument state deletion, file name '{InstrumenterState.ItemSpec}' exception message '{ex.Message}'");
                }

                CoverageResult result = coverage.GetCoverageResult();

                string directory = Path.GetDirectoryName(Output);
                if (directory == string.Empty)
                {
                    directory = Directory.GetCurrentDirectory();
                }
                else if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                string[] formats             = OutputFormat.Split(',');
                var      coverageReportPaths = new List <ITaskItem>(formats.Length);
                ISourceRootTranslator sourceRootTranslator = ServiceProvider.GetService <ISourceRootTranslator>();
                foreach (string format in formats)
                {
                    IReporter reporter = new ReporterFactory(format).CreateReporter();
                    if (reporter == null)
                    {
                        throw new Exception($"Specified output format '{format}' is not supported");
                    }

                    if (reporter.OutputType == ReporterOutputType.Console)
                    {
                        // Output to console
                        Console.WriteLine("  Outputting results to console");
                        Console.WriteLine(reporter.Report(result, sourceRootTranslator));
                    }
                    else
                    {
                        ReportWriter writer = new(CoverletMultiTargetFrameworksCurrentTFM,
                                                  directory,
                                                  Output,
                                                  reporter,
                                                  fileSystem,
                                                  ServiceProvider.GetService <IConsole>(),
                                                  result,
                                                  sourceRootTranslator);
                        string path     = writer.WriteReport();
                        var    metadata = new Dictionary <string, string> {
                            ["Format"] = format
                        };
                        coverageReportPaths.Add(new TaskItem(path, metadata));
                    }
                }

                ReportItems = coverageReportPaths.ToArray();

                var thresholdTypeFlagQueue = new Queue <ThresholdTypeFlags>();

                foreach (string thresholdType in ThresholdType.Split(',').Select(t => t.Trim()))
                {
                    if (thresholdType.Equals("line", StringComparison.OrdinalIgnoreCase))
                    {
                        thresholdTypeFlagQueue.Enqueue(ThresholdTypeFlags.Line);
                    }
                    else if (thresholdType.Equals("branch", StringComparison.OrdinalIgnoreCase))
                    {
                        thresholdTypeFlagQueue.Enqueue(ThresholdTypeFlags.Branch);
                    }
                    else if (thresholdType.Equals("method", StringComparison.OrdinalIgnoreCase))
                    {
                        thresholdTypeFlagQueue.Enqueue(ThresholdTypeFlags.Method);
                    }
                }

                var thresholdTypeFlagValues = new Dictionary <ThresholdTypeFlags, double>();
                if (Threshold.Contains(','))
                {
                    IEnumerable <string> thresholdValues = Threshold.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(t => t.Trim());
                    if (thresholdValues.Count() != thresholdTypeFlagQueue.Count)
                    {
                        throw new Exception($"Threshold type flag count ({thresholdTypeFlagQueue.Count}) and values count ({thresholdValues.Count()}) doesn't match");
                    }

                    foreach (string threshold in thresholdValues)
                    {
                        if (double.TryParse(threshold, out double value))
                        {
                            thresholdTypeFlagValues[thresholdTypeFlagQueue.Dequeue()] = value;
                        }
                        else
                        {
                            throw new Exception($"Invalid threshold value must be numeric");
                        }
                    }
                }
                else
                {
                    double thresholdValue = double.Parse(Threshold);

                    while (thresholdTypeFlagQueue.Any())
                    {
                        thresholdTypeFlagValues[thresholdTypeFlagQueue.Dequeue()] = thresholdValue;
                    }
                }

                ThresholdStatistic thresholdStat = ThresholdStatistic.Minimum;
                if (ThresholdStat.Equals("average", StringComparison.OrdinalIgnoreCase))
                {
                    thresholdStat = ThresholdStatistic.Average;
                }
                else if (ThresholdStat.Equals("total", StringComparison.OrdinalIgnoreCase))
                {
                    thresholdStat = ThresholdStatistic.Total;
                }

                var coverageTable = new ConsoleTable("Module", "Line", "Branch", "Method");
                var summary       = new CoverageSummary();

                CoverageDetails linePercentCalculation   = summary.CalculateLineCoverage(result.Modules);
                CoverageDetails branchPercentCalculation = summary.CalculateBranchCoverage(result.Modules);
                CoverageDetails methodPercentCalculation = summary.CalculateMethodCoverage(result.Modules);

                double totalLinePercent   = linePercentCalculation.Percent;
                double totalBranchPercent = branchPercentCalculation.Percent;
                double totalMethodPercent = methodPercentCalculation.Percent;

                double averageLinePercent   = linePercentCalculation.AverageModulePercent;
                double averageBranchPercent = branchPercentCalculation.AverageModulePercent;
                double averageMethodPercent = methodPercentCalculation.AverageModulePercent;

                foreach (KeyValuePair <string, Documents> module in result.Modules)
                {
                    double linePercent   = summary.CalculateLineCoverage(module.Value).Percent;
                    double branchPercent = summary.CalculateBranchCoverage(module.Value).Percent;
                    double methodPercent = summary.CalculateMethodCoverage(module.Value).Percent;

                    coverageTable.AddRow(Path.GetFileNameWithoutExtension(module.Key), $"{InvariantFormat(linePercent)}%", $"{InvariantFormat(branchPercent)}%", $"{InvariantFormat(methodPercent)}%");
                }

                Console.WriteLine();
                Console.WriteLine(coverageTable.ToStringAlternative());

                coverageTable.Columns.Clear();
                coverageTable.Rows.Clear();

                coverageTable.AddColumn(new[] { "", "Line", "Branch", "Method" });
                coverageTable.AddRow("Total", $"{InvariantFormat(totalLinePercent)}%", $"{InvariantFormat(totalBranchPercent)}%", $"{InvariantFormat(totalMethodPercent)}%");
                coverageTable.AddRow("Average", $"{InvariantFormat(averageLinePercent)}%", $"{InvariantFormat(averageBranchPercent)}%", $"{InvariantFormat(averageMethodPercent)}%");

                Console.WriteLine(coverageTable.ToStringAlternative());

                ThresholdTypeFlags thresholdTypeFlags = result.GetThresholdTypesBelowThreshold(summary, thresholdTypeFlagValues, thresholdStat);
                if (thresholdTypeFlags != ThresholdTypeFlags.None)
                {
                    var exceptionMessageBuilder = new StringBuilder();
                    if ((thresholdTypeFlags & ThresholdTypeFlags.Line) != ThresholdTypeFlags.None)
                    {
                        exceptionMessageBuilder.AppendLine(
                            $"The {thresholdStat.ToString().ToLower()} line coverage is below the specified {thresholdTypeFlagValues[ThresholdTypeFlags.Line]}");
                    }

                    if ((thresholdTypeFlags & ThresholdTypeFlags.Branch) != ThresholdTypeFlags.None)
                    {
                        exceptionMessageBuilder.AppendLine(
                            $"The {thresholdStat.ToString().ToLower()} branch coverage is below the specified {thresholdTypeFlagValues[ThresholdTypeFlags.Branch]}");
                    }

                    if ((thresholdTypeFlags & ThresholdTypeFlags.Method) != ThresholdTypeFlags.None)
                    {
                        exceptionMessageBuilder.AppendLine(
                            $"The {thresholdStat.ToString().ToLower()} method coverage is below the specified {thresholdTypeFlagValues[ThresholdTypeFlags.Method]}");
                    }

                    throw new Exception(exceptionMessageBuilder.ToString());
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex);
                return(false);
            }

            return(true);
        }
Exemplo n.º 49
0
 public string GetExtension(OutputFormat outputFormat)
 {
     return(GetValidExtensions(outputFormat)[0]);
 }
Exemplo n.º 50
0
        public DistanceMatrixResponse GetDistanceMatrixReponse(RequestParameters parameters, OutputFormat outputFormat)
        {
            var format = GetOutputFormatString(outputFormat);
            var url    = $"{format}?{parameters.ToString()}";

            if (cache.ContainsKey(url))
            {
                return(cache[url]);
            }
            else
            {
                var request  = GetRequest(url, Method.GET);
                var response = GetResponse <DistanceMatrixResponse>(request);
                cache.Add(url, response.Data);
                return(response.Data);
            }
        }
Exemplo n.º 51
0
 public Delegate Compile(String template, OutputFormat outputFormat)
 {
     return(CompileInternal(Options.ModelType, template, outputFormat));
 }
Exemplo n.º 52
0
 public OpenTopographyElement(Helper.WGS84 coordinates, RasterDataset dataset = RasterDataset.SRTMGL1, OutputFormat outputFormat = OutputFormat.GTiff)
 {
     this.coordinates  = coordinates;
     this.dataset      = dataset;
     this.outputFormat = outputFormat;
 }
Exemplo n.º 53
0
 public Task <byte[]> RenderAsync(string code, OutputFormat outputFormat)
 {
     return(Task.FromResult(Render(code, outputFormat)));
 }
Exemplo n.º 54
0
        public Uri RenderAsUri(string code, OutputFormat outputFormat)
        {
            string renderUri = renderUrlCalculator.GetRenderUrl(code, outputFormat);

            return(new Uri(renderUri));
        }
Exemplo n.º 55
0
 public Serializer(OutputFormat outputFormat)
 {
     _OutputFormat = outputFormat;
 }
Exemplo n.º 56
0
 private string GetOutputFormat(OutputFormat format)
 {
     return($" --output {Enum.GetName(typeof(OutputFormat), format)?.ToLower()}");
 }
Exemplo n.º 57
0
        static ConvertFileResponse ConvertFile(MarkdownSharp.Markdown markdownToHtml, string inputFileName, string language, IEnumerable <string> languagesLinksToGenerate, OutputFormat format = OutputFormat.HTML)
        {
            var result         = ConvertFileResponse.NoChange;
            var targetFileName = GetTargetFileName(inputFileName, language);

            //Set up parameters in Markdown to aid in processing and generating html
            Markdown.MetadataErrorIfMissing             = MetadataErrorIfMissing;
            Markdown.MetadataInfoIfMissing              = MetadataInfoIfMissing;
            markdownToHtml.DoNotPublishAvailabilityFlag = Settings.Default.DoNotPublishAvailabilityFlag;
            markdownToHtml.PublishFlags             = PublishFlags.ToList();
            markdownToHtml.AllSupportedAvailability = AllSupportedAvailability;

            var fileOutputDirectory = FileHelper.GetRelativePath(
                SourceDirectory, Path.GetDirectoryName(inputFileName));

            var currentFolderDetails = new FolderDetails(
                GetRelativeHTMLPath(targetFileName), OutputDirectory, SourceDirectory, fileOutputDirectory,
                Settings.Default.APIFolderLocation,
                (new DirectoryInfo(inputFileName).Parent).FullName.Replace(
                    SourceDirectory + Path.DirectorySeparatorChar.ToString(), "")
                .Replace(SourceDirectory, "")
                .Replace(Path.DirectorySeparatorChar.ToString(), " - "),
                language);

            markdownToHtml.DefaultTemplate = DefaultTemplate;

            markdownToHtml.ThisIsPreview = ThisIsPreview;

            if (language != "INT")
            {
                currentFolderDetails.DocumentTitle += " - " + language;
            }

            if (ThisIsPreview)
            {
                currentFolderDetails.DocumentTitle += " - PREVIEW!";
            }

            markdownToHtml.SupportedLanguages = SupportedLanguages;

            //Pass the default conversion settings to Markdown for use in the image details creation.
            markdownToHtml.DefaultImageDoCompress      = DoCompressImages;
            markdownToHtml.DefaultImageFormatExtension = CompressImageType;
            markdownToHtml.DefaultImageFillColor       = DefaultImageFillColor;
            markdownToHtml.DefaultImageFormat          = CompressImageFormat;
            markdownToHtml.DefaultImageQuality         = JpegCompressionRate;

            var errorList    = new List <ErrorDetail>();
            var imageDetails = new List <ImageConversion>();
            var attachNames  = new List <AttachmentConversionDetail>();

            var output = markdownToHtml.Transform(FileContents(inputFileName), errorList, imageDetails, attachNames, currentFolderDetails, languagesLinksToGenerate, format != OutputFormat.HTML);

            var noFailedErrorReport = true;
            var stopProcessing      = false;

            //If output empty then treat as failed, we are not converting most likely due to the publish flags and availability settings
            if (String.IsNullOrWhiteSpace(output))
            {
                noFailedErrorReport = false;
                stopProcessing      = true;
                result = ConvertFileResponse.NoChange;
                log.Info(MarkdownSharp.Language.Message("NotConverted", inputFileName));
            }
            else
            {
                //Need to check for error types prior to processing to output log messages in the correct order.
                foreach (var errorInfo in errorList)
                {
                    if (errorInfo.ClassOfMessage == MessageClass.Error || errorInfo.ClassOfMessage == MessageClass.Warning)
                    {
                        log.Info(MarkdownSharp.Language.Message("FileFailed", inputFileName));
                        noFailedErrorReport = false;
                        break;
                    }
                }
            }


            if (noFailedErrorReport)
            {
                log.Info(MarkdownSharp.Language.Message("Converted", inputFileName));
            }


            //On warnings or errors stop processing the file to the publish folder but allow to continue if in preview.
            if (errorList.Count > 0)
            {
                Console.Write("\n");


                foreach (MarkdownSharp.ErrorDetail ErrorInfo in errorList)
                {
                    switch (ErrorInfo.ClassOfMessage)
                    {
                    case MarkdownSharp.MessageClass.Error:
                        log.Error(ErrorInfo.Path ?? inputFileName, ErrorInfo.Line, ErrorInfo.Column, ErrorInfo.Message);
                        if (!ThisIsPreview)
                        {
                            stopProcessing = true;
                            result         = ConvertFileResponse.Failed;
                        }
                        break;

                    case MarkdownSharp.MessageClass.Warning:
                        log.Warn(ErrorInfo.Path ?? inputFileName, ErrorInfo.Line, ErrorInfo.Column, ErrorInfo.Message);
                        if (!ThisIsPreview)
                        {
                            stopProcessing = true;
                            result         = ConvertFileResponse.Failed;
                        }
                        break;

                    default:
                        log.Info(ErrorInfo.Path ?? inputFileName, ErrorInfo.Line, ErrorInfo.Column, ErrorInfo.Message);
                        break;
                    }
                }
            }

            if (!stopProcessing)
            {
                if (ThisIsPreview || !ThisIsLogOnly)
                {
                    CommonUnrealFunctions.CopyDocumentsImagesAndAttachments(inputFileName, log, OutputDirectory, language, fileOutputDirectory, imageDetails, attachNames);
                }

                var expected = FileContents(targetFileName);

                if (output == expected)
                {
                    result = ConvertFileResponse.NoChange;
                }
                else
                {
                    if (!stopProcessing)
                    {
                        if (!AlreadyCreatedCommonDirectories)
                        {
                            AlreadyCreatedCommonDirectories = CommonUnrealFunctions.CreateCommonDirectories(OutputDirectory, SourceDirectory, log);
                        }

                        Console.Write("\n");
                        if (ThisIsPreview || !ThisIsLogOnly)
                        {
                            //Check output directory exists, if not create the full html structure for this language
                            CommonUnrealFunctions.GenerateDocsFolderStructure(OutputDirectory, fileOutputDirectory, language);

                            CommonUnrealFunctions.SetFileAttributeForReplace(new FileInfo(targetFileName));
                            File.WriteAllText(targetFileName, output);

                            if (format == OutputFormat.PDF)
                            {
                                PdfHelper.CreatePdfFromHtml(targetFileName);
                            }
                        }

                        result = ConvertFileResponse.Converted;
                    }
                }
            }
            return(result);
        }
Exemplo n.º 58
0
 internal InstanceSettings(string className, string outputDirectory, OutputFormat language)
 {
     InputFile       = className;
     OutputDirectory = outputDirectory;
     Language        = language;
 }
Exemplo n.º 59
0
        public void ReadArguments(string[] parameters)
        {
            if (parameters.Length == 0)
            {
                //throw new Exception("No parameter is specified!");
                GetHelp = true;
            }

            #region Assigning crexport parameters to variables
            for (int i = 0; i < parameters.Count(); i++)
            {
                if (i + 1 < parameters.Count())
                {
                    if (parameters[i + 1].Length > 0)
                    {
                        if (parameters[i].ToUpper() == "-U")
                        {
                            UserName = parameters[i + 1];
                        }
                        else if (parameters[i].ToUpper() == "-P")
                        {
                            Password = parameters[i + 1];
                        }
                        else if (parameters[i].ToUpper() == "-F")
                        {
                            ReportPath = parameters[i + 1];
                        }
                        else if (parameters[i].ToUpper() == "-O")
                        {
                            OutputPath = parameters[i + 1];
                        }
                        else if (parameters[i].ToUpper() == "-S")
                        {
                            ServerName = parameters[i + 1];
                        }
                        else if (parameters[i].ToUpper() == "-D")
                        {
                            DatabaseName = parameters[i + 1];
                        }
                        else if (parameters[i].ToUpper() == "-E")
                        {
                            OutputFormat = parameters[i + 1]; if (OutputFormat.ToUpper() == "PRINT")
                            {
                                PrintOutput = true;
                            }
                        }
                        else if (parameters[i].ToUpper() == "-N")
                        {
                            PrinterName = parameters[i + 1];
                        }
                        else if (parameters[i].ToUpper() == "-C")
                        {
                            try
                            {
                                PrintCopy = Convert.ToInt32(parameters[i + 1]);
                            }
                            catch (Exception ex)
                            { throw ex; }
                        }
                        else if (parameters[i].ToUpper() == "-A")
                        {
                            ParameterCollection.Add(parameters[i + 1]);
                        }

                        //Email Config
                        else if (parameters[i].ToUpper() == "-M")
                        {
                            EmailOutput = true;
                        }
                        else if (parameters[i].ToUpper() == "-MF")
                        {
                            MailFrom = parameters[i + 1];
                        }
                        else if (parameters[i].ToUpper() == "-MN")
                        {
                            MailFromName = parameters[i + 1];
                        }
                        else if (parameters[i].ToUpper() == "-MS")
                        {
                            EmailSubject = parameters[i + 1];
                        }
                        else if (parameters[i].ToUpper() == "-MI")
                        {
                            EmailBody = parameters[i + 1];
                        }
                        else if (parameters[i].ToUpper() == "-MT")
                        {
                            MailTo = parameters[i + 1];
                        }
                        else if (parameters[i].ToUpper() == "-MC")
                        {
                            MailCC = parameters[i + 1];
                        }
                        else if (parameters[i].ToUpper() == "-MB")
                        {
                            MailBcc = parameters[i + 1];
                        }
                        else if (parameters[i].ToUpper() == "-MK")
                        {
                            EmailKeepFile = true;
                        }
                        else if (parameters[i].ToUpper() == "-MSA")
                        {
                            SmtpServer = parameters[i + 1];
                        }
                        else if (parameters[i].ToUpper() == "-MSP")
                        {
                            SmtpPort = Convert.ToInt32(parameters[i + 1]);
                        }
                        else if (parameters[i].ToUpper() == "-MSE")
                        {
                            SmtpSSL = true;
                        }
                        else if (parameters[i].ToUpper() == "-MSC")
                        {
                            SmtpAuth = true;
                        }
                        else if (parameters[i].ToUpper() == "-MUN")
                        {
                            SmtpUN = parameters[i + 1];
                        }
                        else if (parameters[i].ToUpper() == "-MPW")
                        {
                            SmtpPW = parameters[i + 1];
                        }
                        else if (parameters[i].ToUpper() == "-SF")
                        {
                            SelectionFormula = parameters[i + 1];
                        }
                    }
                }

                if (parameters[i] == "-?" || parameters[i] == "/?")
                {
                    GetHelp = true;
                }

                if (parameters[i].ToUpper() == "-L")
                {
                    EnableLog = true;
                }

                if (parameters[i].ToUpper() == "-NR")
                {
                    Refresh = false;
                }

                if (parameters[i].ToUpper() == "-LC")
                {
                    EnableLogToConsole = true;
                }
            }
            #endregion
        }
Exemplo n.º 60
0
 public GraphTraversal2(GraphViewConnection connection, OutputFormat outputFormat)
 {
     this.connection   = connection;
     this.outputFormat = outputFormat;
 }