Ejemplo n.º 1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="apiName"></param>
        /// <param name="param"></param>
        /// <param name="format"></param>
        /// <param name="version"></param>
        /// <returns></returns>
        private static string GetSign(string apiName, Dictionary <string, string> param, FormatType format = FormatType.Json, string version = "3.0")
        {
            param = param ?? new Dictionary <string, string>();
            param = param.ToOrdinalIgnoreCase();
            param.AddItem("appid", AppId);
            if (apiName.IndexOf("vast.") > -1)
            {
                param.AddItem("method", apiName);
            }
            else
            {
                param.AddItem("method", "linker." + apiName);
            }
            param.AddItem("timestamp", Utils.GetTimstamp().ToString());
            param.AddItem("v", version);
            //if (!param.ContainsKey("fkid"))
            //    param.AddItem("fkid", FKId.ToString());
            //if (!param.ContainsKey("fkflag"))
            //    param.AddItem("fkflag", FKFlag.ToString());
            param.AddItem("format", format.ToString());
            ////默认加上运营主体
            //if (!(apiName.ToLower() == "vast.core.domain.getfkid" || apiName.ToLower() == "vast.core.domain.getproprietordomain"))
            //{
            //    if (!param.ContainsKey("proprietorid"))
            //    {
            //        param.AddItem("proprietorid", DnsRoute.ProprietorId.ToString());
            //    }
            //}
            Dictionary <string, string> sordDic = param.SortFilter();
            string sign = ECF.Security.Encrypt.MD532(sordDic.ToLinkString() + "&secret=" + Secret);

            return(param.ToLinkString() + "&sign=" + sign);
        }
Ejemplo n.º 2
0
 public Nominatim(FormatType format, PolygonType polygon, AddressDetailsType addressDetail)
 {
     _format        = format;
     _polygon       = polygon;
     _addressDetail = addressDetail;
     _search        = _searchUrl + "format=" + format.ToString() + "&polygon=" + (int)polygon + "&addressdetails=" + (int)addressDetail + "&q=";
 }
Ejemplo n.º 3
0
        // NHL,[Sources],[Symbols],[XML/Text],[Limit],[Date],[RequestID]
        public string ReqNewsHeadlines(string[] sources = null, string[] symbols = null, FormatType?formatType = null, int?limit = null, DateTime?date = null, string requestId = null)
        {
            var sourcesCsv      = string.Join(";", sources ?? Array.Empty <string>());
            var symbolsCsv      = string.Join(";", symbols ?? Array.Empty <string>());
            var formattedFormat = formatType?.ToString().ToLowerInvariant().Substring(0, 1);

            return($"NHL,{sourcesCsv},{symbolsCsv},{formattedFormat},{limit},{date.ToInvariantString(NewsDateFormat)},{requestId}{IQFeedDefault.ProtocolTerminatingCharacters}");
        }
Ejemplo n.º 4
0
        // NSC,[Symbols],[XML/Text],[Sources],[DateRange],[RequestID]<CR>
        public string ReqNewsStoryCount(string[] symbols, FormatType?formatType = null, string[] sources = null, DateTime?fromDate = null, DateTime?toDate = null, string requestId = null)
        {
            var symbolsCsv      = string.Join(";", symbols ?? Array.Empty <string>());
            var formattedFormat = formatType?.ToString().ToLowerInvariant().Substring(0, 1);
            var sourcesCsv      = string.Join(";", sources ?? Array.Empty <string>());
            var dateRange       = fromDate.HasValue && toDate.HasValue ? $"{fromDate.ToInvariantString(NewsDateFormat)}-{toDate.ToInvariantString(NewsDateFormat)}" : fromDate.ToInvariantString(NewsDateFormat);

            return($"NSC,{symbolsCsv},{formattedFormat},{sourcesCsv},{dateRange},{requestId}{IQFeedDefault.ProtocolTerminatingCharacters}");
        }
Ejemplo n.º 5
0
 internal void Persist(XmlWriter writer)
 {
     writer.WriteStartElement("Condition");
     writer.WriteElementString("ColumnName", ColumnName);
     writer.WriteElementString("FormatType", FormatType.ToString());
     writer.WriteStartElement("FormatParams");
     FormatParams.Persist(writer);
     writer.WriteEndElement(); //FormatParams
     //No need to persist min/max Value.
     writer.WriteEndElement(); //Condition
 }
Ejemplo n.º 6
0
        public static bool FormatVerification(string verifyingString, FormatType formatType,
                                              System.Exception formatErrorExceptionType = null)
        {
            var method = typeof(FormatVerificationHelper).GetMethod($"{formatType.ToString()}Verification");
            var pass   = (bool)method.Invoke(null, new object[] { verifyingString });

            if (formatErrorExceptionType != null && !pass)
            {
                throw formatErrorExceptionType;
            }
            return(pass);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Menggenerate format yg compatible dengan C# atau kendo
        /// </summary>
        /// <param name="formatType">jenis format</param>
        /// <param name="isCSharpFormat">jika ya, maka akan digunakan {0:format}</param>
        /// <param name="decimalPoint">jumlah digit desimal</param>
        /// <param name="suffix">tambahan kata di akhir</param>
        /// <param name="prefix">tambahan kata di awal</param>
        /// <param name="dateFormat">custom date format (default: yyyy-MM-dd)</param>
        /// <param name="forcePaddingZero">paksa isi dengan angka 0 jika nilai decimal tidak ada (hanya jika <paramref name="decimalPoint"/> &gt; 0</param>
        /// <returns>string</returns>
        private static string PrepareFormat(FormatType formatType, bool isCSharpFormat = true, int decimalPoint = 2, string suffix = "", string prefix = "", string dateFormat = "", bool forcePaddingZero = true)
        {
            string format            = string.Empty;
            string defaultDateFormat = DEFAULT_DATEFORMAT;

            switch (formatType)
            {
            case FormatType.Numeric:
            case FormatType.Percentage:
                format = "#" + THOUSAND_SEPARATOR + (forcePaddingZero ? "0" : "#");
                break;

            case FormatType.NumericWithDecimalPoint:
            case FormatType.PercentageWithDecimalPoint:
                format = "#" + THOUSAND_SEPARATOR + (forcePaddingZero ? "0" : "#");
                if (decimalPoint > 0)
                {
                    format += DECIMAL_SEPARATOR + new System.String(forcePaddingZero ? '0' : '#', decimalPoint);
                }
                break;

            case FormatType.Date:
                format = string.IsNullOrEmpty(dateFormat) ? defaultDateFormat : dateFormat;
                break;

            case FormatType.Time:
                format = DEFAULT_TIMEFORMAT;
                break;

            case FormatType.DateTime:
                format = (string.IsNullOrEmpty(dateFormat) ? defaultDateFormat : dateFormat) + " " + DEFAULT_TIMEFORMAT;
                break;
            }
            //untuk format C#, harus menggunakan {x:#} dst
            if (isCSharpFormat)
            {
                format = "{0:" + format + "}";
            }
            //karakter tambahan harus diluar {x}
            if (formatType.ToString().Contains("Percentage"))
            {
                format += " %";
            }
            if (!string.IsNullOrEmpty(prefix))
            {
                format = prefix + " " + format;
            }
            if (!string.IsNullOrEmpty(suffix))
            {
                format += " " + suffix;
            }
            return(format);
        }
Ejemplo n.º 8
0
 public YopRequest()
 {
     this.appKey     = YopConfig.getAppKey();
     this.secretKey  = YopConfig.getSecret();
     this.serverRoot = YopConfig.getServerRoot();
     if (YopConfig.getAppKey() != null)
     {
         paramMap.Add(YopConstants.APP_KEY, YopConfig.getAppKey());
     }
     paramMap.Add(YopConstants.FORMAT, format.ToString());
     paramMap.Add(YopConstants.VERSION, version);
     paramMap.Add(YopConstants.LOCALE, locale);
     paramMap.Add(YopConstants.TIMESTAMP, TimeStamp.GetTimeStamp().ToString());
 }
Ejemplo n.º 9
0
        /// <summary>
        /// GEt Tencent Pure text content request url
        /// </summary>
        /// <param name="requestUrl">request url</param>
        /// <param name="formatType">format type</param>
        /// <param name="content">send content</param>
        /// <param name="clientIp">client ip address</param>
        /// <returns>request url</returns>
        public string GetPureTextContentUrl(string requestUrl, string appkey, string accesstoken, string openid, string content, FormatType format, string clientip = "",
                                            string oauthVersion = "2.a", string scope = "all")
        {
            requestUrl += "t/add";
            #region merge all post argument to list
            if (PostArgumentList == null)
            {
                PostArgumentList = new List <KeyValuePair <string, object> >();
            }
            PostArgumentList.Add(new KeyValuePair <string, object>("oauth_consumer_key", appkey));
            PostArgumentList.Add(new KeyValuePair <string, object>("access_token", accesstoken));
            PostArgumentList.Add(new KeyValuePair <string, object>("openid", openid));

            PostArgumentList.Add(new KeyValuePair <string, object>("clientip", clientip));
            PostArgumentList.Add(new KeyValuePair <string, object>("oauth_version", oauthVersion));
            PostArgumentList.Add(new KeyValuePair <string, object>("scope", scope));

            PostArgumentList.Add(new KeyValuePair <string, object>("format", format.ToString().ToLower()));
            PostArgumentList.Add(new KeyValuePair <string, object>("content", content));
            #endregion
            return(requestUrl);
        }
Ejemplo n.º 10
0
        private static string ChangeFileExtension(string file, FormatType format)
        {
            string ext = format.ToString().ToUpper();

            if (Path.HasExtension(file))
            {
                string x = Path.GetExtension(file).ToUpper();
                if (x == ".PC")
                {
                    file = Path.ChangeExtension(file, null);
                }
                x = Path.GetExtension(file).ToUpper();
                if (x == ".MBIN")
                {
                    return(Path.ChangeExtension(file, ext));
                }
                if (x == ".EXML")
                {
                    return(Path.ChangeExtension(file, ext));
                }
            }
            return(file + $".{ext}");
        }
Ejemplo n.º 11
0
        public TemplateProvider(Type type, FormatType formatType)
        {
            var resourceName =
                type.Assembly.GetManifestResourceNames()
                .FirstOrDefault(q => q.Contains(".Template." + formatType.ToString()));

            if (resourceName != null)
            {
                using (var stream = type.Assembly.GetManifestResourceStream(resourceName))
                {
                    if (stream != null)
                    {
                        using (var reader = new StreamReader(stream))
                        {
                            _template = reader.ReadToEnd();
                        }
                    }
                    else
                    {
                        _template = resourceName;
                    }
                }
            }
        }
Ejemplo n.º 12
0
        public static StreamInfo BuildThumb(StreamInfo file, FormatType format, RatioType ratio, uint width, uint height) {
            using(file) {
                
                //The mimetype of the thumb is based on the formattype. The 
                MimeType mime = ResolvePreviewMime(ref format);                

                //Some basic DoS protection.
                if(!IsPreviewSizeAllowed(width, height)) {
                    throw new Exceptions.ImagePreviewOversizedInvalidArgumentException();
                }
                string thumbnailArgs = string.Empty;
                if(width > 0 || height > 0) {
                    thumbnailArgs = string.Format("-colorspace RGB -thumbnail {0}{1}{2}{3}", width == 0 ? "" : width.ToString(), height > 0 ? "x" : "", height == 0 ? string.Empty : height.ToString(), ratio == RatioType.FIXED || ratio == RatioType.UNDEFINED ? "" : "!");
                }

                // NOTE (steveb): the '-[0]' option means that we only want to convert the first frame if there are multiple frames
                string args = string.Format("{0} -[0] {1}-", thumbnailArgs, (format == FormatType.UNDEFINED) ? string.Empty : format.ToString() + ":");

                Stopwatch sw = Stopwatch.StartNew();

                // run ImageMagick application
                Tuplet<int, Stream, Stream> exitValues = Async.ExecuteProcess(DekiContext.Current.Deki.ImageMagickConvertPath, args, file.Stream, new Result<Tuplet<int, Stream, Stream>>(TimeSpan.FromMilliseconds(DekiContext.Current.Deki.ImageMagickTimeout))).Wait();

                // record stats about this imagemagick execution
                sw.Stop();
                AddToStats(HEADERSTAT_CONVERT, sw.ElapsedMilliseconds);
                int status = exitValues.Item1;
                Stream outputStream = exitValues.Item2;
                Stream errorStream = exitValues.Item3;

                if(outputStream.Length == 0) {
                    using(StreamReader error = new StreamReader(errorStream)) {
                        _log.WarnMethodCall("Imagemagick convert failed", args, status, error.ReadToEnd());
                    }
                    return null;
                }
                _log.InfoFormat("Imagemagick convert finished in {0}ms. Args:{1}", sw.ElapsedMilliseconds, args);
                return new StreamInfo(outputStream, outputStream.Length, mime);
            }
        }
Ejemplo n.º 13
0
 protected BaseFormat(FormatType format)
     : this(FormattingUtility.Library(format.ToString()))
 {
 }
Ejemplo n.º 14
0
        public static int ConvertQEMU(FormatType fromFormat, FormatType toFormat, String FromFolderWithFile, String FileName, String SaveFolderPath)
        {
            try
            {
                //qemu-img convert -f raw -O qcow2 image.img image.qcow2
                // String args = null;

                Log.Debug(TAG + "Will start to convert " + fromFormat + " to " + toFormat);

                string fromFromatArgs = fromFormat.ToString().ToLower();
                string toFromatArgs   = toFormat.ToString().ToLower();

                if (fromFromatArgs.Equals("vhd"))
                {
                    fromFromatArgs = "vpc";
                }
                if (toFromatArgs.Equals("vhd"))
                {
                    toFromatArgs = "vpc";
                }

                String Arguments = "/c Tools\\qemu-img-win-x64-2_3_0\\qemu-img.exe convert -f " + fromFromatArgs + " -O " + toFromatArgs
                                   + " " + "\"" + FromFolderWithFile + "\"" + " " + "\"" + SaveFolderPath + @"\" + FileName + "." + toFormat.ToString().ToLower() + "\"";

                //Misc.Utils.StartProcess(Arguments,"Tools\\qemu-img-win-x64-2_3_0\\qemu-img.exe");

                Log.Debug(TAG + "Command: " + Arguments);
                ErrorFlag = false;
                var proc = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName  = "cmd.exe",
                        Arguments = Arguments,
                    }
                };

                proc.StartInfo.UseShellExecute        = false;
                proc.StartInfo.CreateNoWindow         = true;
                proc.EnableRaisingEvents              = true;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardError  = true;
                proc.Start();

                var std_out_error_reader = proc.StandardError;
                var std_out_data_reader  = proc.StandardOutput;
                WriteToLog(std_out_data_reader, "d");
                WriteToLog(std_out_error_reader, "e");

                proc.WaitForExit();

                if (ErrorFlag)
                {
                    Log.Error(TAG + "Failed to convert the disks.");
                    return(1);
                }
                else
                {
                    Log.Debug(TAG + "Converted " + toFormat + " disk from " + fromFormat + ". Converted disk saved at :"
                              + SaveFolderPath + @"\" + FileName + "." + toFormat.ToString().ToLower());

                    MessageBox.Show("Converted " + toFormat + " disk from " + fromFormat + ".Converted disk saved at: "
                                    + SaveFolderPath + @"\" + FileName + "." + toFormat.ToString().ToLower());
                    return(0);
                }
            }
            catch (Exception ex)
            {
                Misc.Utils.ExceptionHandleMsg(TAG, "Could not convert the image.", ex);
                Misc.Utils.ErrorBox("Could not convert the image.", ex);
                return(1);
            }
        }
Ejemplo n.º 15
0
 private static int GetNativeSize(FormatType c) {
     switch (c) {
         case FormatType.Char:
         case FormatType.SignedChar:
         case FormatType.UnsignedChar:
         case FormatType.PadByte:
         case FormatType.Bool:
         case FormatType.CString:
         case FormatType.PascalString:
             return 1;
         case FormatType.Short:
         case FormatType.UnsignedShort:
             return 2;
         case FormatType.Int:
         case FormatType.UnsignedInt:
         case FormatType.UnsignedLong:
         case FormatType.Float:
             return 4;
         case FormatType.LongLong:
         case FormatType.UnsignedLongLong:
         case FormatType.Double:
             return 8;
         case FormatType.Pointer:
             return IntPtr.Size;
         default:
             throw new InvalidOperationException(c.ToString());
     }
 }
Ejemplo n.º 16
0
        /// <summary>
        /// 返回字符串加解密
        /// </summary>
        /// <param name="DataSetString">字符串内容</param>
        /// <param name="CodeType">FormatType类型</param>
        /// <returns></returns>
        public string FormatReturnString(string DataSetXMLString, FormatType CodeType)
        {
            string RetStr = "";

            try
            {
                switch (CodeType)
                {
                case FormatType.DeCode:
                    //utf-8的编码代码页是65001
                    RetStr = HttpUtility.UrlDecode(DataSetXMLString, System.Text.Encoding.GetEncoding(65001));
                    break;

                case FormatType.EnCode:
                    //65001   utf-8   Unicode(UTF-8)
                    RetStr = HttpUtility.UrlEncode(DataSetXMLString, System.Text.Encoding.GetEncoding(65001));
                    break;
                }
                _errorInfo = "";
            }
            catch (Exception ex)
            {
                _errorInfo = Log.LogLib.GetExceptionInfo(ex, "Peer.PublicCsharpModule.xml->ClassicXML->FormatReturnString", string.Format("{0}->{1}", DataSetXMLString, CodeType.ToString()));
            }
            return(RetStr);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// 编码或者解码方式格式化POST到IIS的字符串数据
        /// </summary>
        /// <param name="PostData">post的字符串内容</param>
        /// <param name="CodeType">FormatType类型</param>
        /// <returns></returns>
        public string FormatDeEnString(string PostData, FormatType CodeType)
        {
            string RetStr = "";

            try
            {
                switch (CodeType)
                {
                case FormatType.DeCode:
                    //utf-8的编码代码页是65001
                    RetStr = HttpUtility.UrlDecode(PostData, System.Text.Encoding.GetEncoding(65001));
                    break;

                case FormatType.EnCode:
                    //65001   utf-8   Unicode(UTF-8)
                    //两次编码解决原理:https://blog.csdn.net/xjaaaxl/article/details/60868692
                    RetStr = HttpUtility.UrlEncode(HttpUtility.UrlEncode(PostData, System.Text.Encoding.GetEncoding(65001)));
                    break;
                }
                _errorInfo = "";
            }
            catch (Exception ex)
            {
                _errorInfo = Log.LogLib.GetExceptionInfo(ex, "Peer.PublicCsharpModule.xml->ClassicXML->FormatString", string.Format("{0}->{1}", PostData, CodeType.ToString()));
            }
            return(RetStr);
        }
Ejemplo n.º 18
0
        // NCG,[XML/Text],[RequestID]<CR><LF>
        public string ReqNewsConfiguration(FormatType formatType, string requestId = null)
        {
            var formattedFormat = formatType.ToString().ToLowerInvariant().Substring(0, 1);

            return($"NCG,{formattedFormat},{requestId}{IQFeedDefault.ProtocolTerminatingCharacters}");
        }
        public Dictionary<String, String> RefreshSignParameters(Dictionary<String, String> parameters,
                ISigner signer, String accessKeyId, FormatType? format)
        {
            Dictionary<String, String> immutableMap = new Dictionary<String, String>(parameters);

            DictionaryUtil.Add(immutableMap, "Timestamp", ParameterHelper.FormatIso8601Date(DateTime.Now));
            DictionaryUtil.Add(immutableMap, "SignatureMethod", signer.SignerName);
            DictionaryUtil.Add(immutableMap, "SignatureVersion", signer.SignerVersion);
            DictionaryUtil.Add(immutableMap, "SignatureNonce", Guid.NewGuid().ToString());
            DictionaryUtil.Add(immutableMap, "AccessKeyId", accessKeyId);
            DictionaryUtil.Add(immutableMap, "Format", format.ToString());

            return immutableMap;
        }
Ejemplo n.º 20
0
        public static StreamInfo BuildThumb(StreamInfo file, FormatType format, RatioType ratio, uint width, uint height)
        {
            using (file) {
                //The mimetype of the thumb is based on the formattype. The
                MimeType mime = ResolvePreviewMime(ref format);

                //Some basic DoS protection.
                if (!IsPreviewSizeAllowed(width, height))
                {
                    throw new Exceptions.ImagePreviewOversizedInvalidArgumentException();
                }
                string thumbnailArgs = string.Empty;
                if (width > 0 || height > 0)
                {
                    thumbnailArgs = string.Format("-colorspace RGB -thumbnail {0}{1}{2}{3}", width == 0 ? "" : width.ToString(), height > 0 ? "x" : "", height == 0 ? string.Empty : height.ToString(), ratio == RatioType.FIXED || ratio == RatioType.UNDEFINED ? "" : "!");
                }

                // NOTE (steveb): the '-[0]' option means that we only want to convert the first frame if there are multiple frames
                string args = string.Format("{0} -[0] {1}-", thumbnailArgs, (format == FormatType.UNDEFINED) ? string.Empty : format.ToString() + ":");

                Stopwatch sw = Stopwatch.StartNew();

                // run ImageMagick application
                Tuplet <int, Stream, Stream> exitValues = Async.ExecuteProcess(DekiContext.Current.Deki.ImageMagickConvertPath, args, file.Stream, new Result <Tuplet <int, Stream, Stream> >(TimeSpan.FromMilliseconds(DekiContext.Current.Deki.ImageMagickTimeout))).Wait();

                // record stats about this imagemagick execution
                sw.Stop();
                AddToStats(HEADERSTAT_CONVERT, sw.ElapsedMilliseconds);
                int    status       = exitValues.Item1;
                Stream outputStream = exitValues.Item2;
                Stream errorStream  = exitValues.Item3;

                if (outputStream.Length == 0)
                {
                    using (StreamReader error = new StreamReader(errorStream)) {
                        _log.WarnMethodCall("Imagemagick convert failed", args, status, error.ReadToEnd());
                    }
                    return(null);
                }
                _log.InfoFormat("Imagemagick convert finished in {0}ms. Args:{1}", sw.ElapsedMilliseconds, args);
                return(new StreamInfo(outputStream, outputStream.Length, mime));
            }
        }
       /// <summary>
       /// GEt Tencent Pure text content request url
       /// </summary>
       /// <param name="requestUrl">request url</param>
       /// <param name="formatType">format type</param>
       /// <param name="content">send content</param>
       /// <param name="clientIp">client ip address</param>
       /// <returns>request url</returns>
       public string GetPureTextContentUrl(string requestUrl, string appkey, string accesstoken, string openid, string content, FormatType format, string clientip="",
           string oauthVersion = "2.a",string scope="all")
       {
           requestUrl += "t/add";
           #region merge all post argument to list
           if (PostArgumentList == null)
               PostArgumentList = new List<KeyValuePair<string, object>>();
           PostArgumentList.Add(new KeyValuePair<string, object>("oauth_consumer_key", appkey));
           PostArgumentList.Add(new KeyValuePair<string, object>("access_token", accesstoken));
           PostArgumentList.Add(new KeyValuePair<string, object>("openid", openid));

           PostArgumentList.Add(new KeyValuePair<string, object>("clientip", clientip));
           PostArgumentList.Add(new KeyValuePair<string, object>("oauth_version", oauthVersion));
           PostArgumentList.Add(new KeyValuePair<string, object>("scope", scope));

           PostArgumentList.Add(new KeyValuePair<string, object>("format", format.ToString().ToLower()));
           PostArgumentList.Add(new KeyValuePair<string, object>("content", content));
           #endregion
           return requestUrl;
       }
Ejemplo n.º 22
0
 public static string Library(FormatType codec)
 {
     return(Library(codec.ToString()));
 }
Ejemplo n.º 23
0
        /// <summary>
        /// Takes a screenshot from an Url.
        /// </summary>
        /// <param name="accessKey">A valid access key allowing you to make API calls.</param>
        /// <param name="url">The complete URL of the website for which you want to capture a screenshot. The URL must include the protocol (http:// or https://) to be processed correctly.</param>
        /// <param name="format">The image format of the captured screenshot. Either jpeg or png.</param>
        /// <param name="failOnStatus">A comma separated list of HTTP status codes that should make the API call fail instead of returning a screenshot. Hyphen separated HTTP status codes can be used to define ranges. For example 400,404,500-511 would make the API call fail if the URL returns 400, 404 or any status code between 500 and 511.</param>
        /// <param name="ttl">Number of seconds the screenshot is cached. API calls with the same parameters do return a cached screenshot and don't count in your monthly quota. From 0 seconds to 2592000 seconds (30 days).</param>
        /// <param name="fresh">Force the API to capture a fresh new screenshot instead of returning a screenshot from the cache.</param>
        /// <param name="fullPage">Set this parameter to true to capture the entire page of the target website.</param>
        /// <param name="scrollPage">Set this parameter to true to scroll through the entire page before capturing a screenshot. This is useful to trigger animations or lazy loaded elements.</param>
        /// <param name="width">The width, in pixels, of the viewport to use.</param>
        /// <param name="height">The height, in pixels, of the viewport to use. This is ignored if FullPage is true.</param>
        /// <param name="delay">The delay, in seconds, to wait after the page is loaded (load event fired and no more network connections for at least 500ms) before capturing the screenshot. From 0 seconds to a maximum of 10 seconds.</param>
        /// <param name="waitFor">Wait until the provided CSS selector matches an element present in the page before capturing a screenshot. The process times out after 40 seconds.</param>
        /// <param name="quality">The quality of the image between 0 and 100. This only works with the jpeg format.</param>
        /// <param name="transparent">Hides the default background and allows capturing screenshots with transparency. This only works with the png format.</param>
        /// <param name="thumbnailWidth">The width, in pixels, of the thumbnail to generate. The aspect ratio will be preserved. This is ignored if FullPage is true.</param>
        /// <param name="scaleFactor">The device scale factor to use when capturing the screenshot. A scale factor of 2 will produce a high definition screenshot suited to be displayed on retina devices. The bigger the scale factor is, the heavier the produced screenshot will be.</param>
        /// <param name="css">A CSS string to inject in the web page when capturing the screenshot. This CSS string needs to be URL encoded to be processed correctly.</param>
        /// <param name="js">Additional JavaScript code to be injected into the page before capturing. The JS string needs to be URL encoded to be processed correctly.</param>
        /// <param name="extractHtml">Extract the HTML of the page at the same time the screenshot is made. When this parameter is set to true, an ExtractedHtml attribute is added to the returned json document.</param>
        /// <param name="extractText">Extract the text of the page at the same time the screenshot is made. When this parameter is set to true, an ExtractedText attribute is added to the returned json document.</param>
        /// <param name="acceptLanguage">Sets the Accept-Language header on requests to the target URL allowing you to make screenshots of a website with a specific language.</param>
        /// <param name="userAgent">Sets the User-Agent header to emulate a particular device when making screenshots. It should be URL encoded to be processed correctly.</param>
        /// <param name="headers">A semicolon separated list of headers to be used when capturing the screenshot. Each header should be supplied as a key value pair and multiple pairs should be separated by a semicolon. The Headers parameter value should be URL encoded to be processed correctly. For example, Header1=value1;Header2=value2 would have to be URL encoded into Header1%3Dvalue1%3BHeader2%3Dvalue2.</param>
        /// <param name="cookies">A semicolon separated list of cookies to be used when capturing the screenshot. Each cookie should be supplied as a name value pair and multiple pairs should be separated by a semicolon. The Cookies parameter value should be URL encoded to be processed correctly. For example, cookie1=value1;cookie2=value2 would have to be URL encoded into cookie1%3Dvalue1%3Bcookie2%3Dvalue2.</param>
        /// <param name="latitude">The latitude to use when emulating geo-location between -90 and 90.</param>
        /// <param name="longitude">The longitude to use when emulating geo-location between -180 and 180.</param>
        /// <param name="accuracy">Accuracy value to use when emulating geo-location.</param>
        /// <param name="proxy">The address of a proxy server through which the screenshot should be captured. The proxy address should be formatted as address:port or user:password@address:port if authentication is needed.</param>
        /// <returns>An ApiFlashResponse object containing the Url of the image or the error message.</returns>
        public static async Task <ApiFlashResponse> UrlToImageAsync(string accessKey, string url, FormatType format = FormatType.Jpeg, string failOnStatus = "",
                                                                    uint ttl         = 86400, bool fresh = false, bool fullPage = false, bool scrollPage        = false,
                                                                    uint width       = 1920, uint height = 1080, uint delay     = 0, string waitFor             = "", uint quality = 80,
                                                                    bool transparent = false, uint thumbnailWidth   = 0, uint scaleFactor  = 1, string css      = "", string js    = "", bool extractHtml = false,
                                                                    bool extractText = false, string acceptLanguage = "", string userAgent = "", string headers = "", string cookies = "", int latitude   = 0,
                                                                    int longitude    = 0, uint accuracy = 0, string proxy = "")
        {
            if (string.IsNullOrEmpty(accessKey))
            {
                throw new ArgumentNullException(nameof(accessKey));
            }
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException(nameof(url));
            }
            if (!Uri.IsWellFormedUriString(url, UriKind.Absolute))
            {
                throw new ArgumentException("The Url is not well formed.", nameof(url));
            }

            var query = HttpUtility.ParseQueryString(string.Empty);

            query["access_key"]    = accessKey;
            query["url"]           = url;
            query["response_type"] = ResponseType.Json.ToString().ToLowerInvariant();

            if (format != FormatType.Jpeg)
            {
                query["format"] = format.ToString().ToLowerInvariant();
            }
            if (!string.IsNullOrEmpty(failOnStatus)) // check valid
            {
                query["fail_on_status"] = failOnStatus;
            }
            if (ttl != 86400)
            {
                if (ttl > 2592000)
                {
                    throw new ArgumentOutOfRangeException(nameof(ttl), ttl, "Value must be between 0 and 2592000.");
                }
                query["ttl"] = ttl.ToString();
            }
            if (fresh)
            {
                query["fresh"] = "true";
            }
            if (fullPage)
            {
                query["full_page"] = "true";
            }
            if (scrollPage)
            {
                query["scroll_page"] = "true";
            }
            if (width != 1920)
            {
                query["width"] = width.ToString();
            }
            if (height != 1080 && !fullPage)
            {
                query["height"] = height.ToString();
            }
            if (delay != 0)
            {
                if (delay > 10)
                {
                    throw new ArgumentOutOfRangeException(nameof(delay), delay, "Value must be between 0 and 10.");
                }
                query["delay"] = delay.ToString();
            }
            if (!string.IsNullOrEmpty(waitFor))
            {
                query["wait_for"] = waitFor;
            }
            if (quality != 80)
            {
                if (quality > 100)
                {
                    throw new ArgumentOutOfRangeException(nameof(quality), quality, "Value must be between 0 and 100.");
                }
                query["quality"] = quality.ToString();
            }
            if (transparent && format == FormatType.Png)
            {
                query["transparent"] = "true";
            }
            if (thumbnailWidth != 0 && !fullPage)
            {
                query["thumbnail_width"] = thumbnailWidth.ToString();
            }
            if (scaleFactor != 1)
            {
                query["scale_factor"] = scaleFactor.ToString();
            }
            if (!string.IsNullOrEmpty(css))
            {
                query["css"] = css;
            }
            if (!string.IsNullOrEmpty(js))
            {
                query["js"] = js;
            }
            if (extractHtml)
            {
                query["extract_html"] = "true";
            }
            if (extractText)
            {
                query["extract_text"] = "true";
            }
            if (!string.IsNullOrEmpty(acceptLanguage))
            {
                query["accept_language"] = acceptLanguage;
            }
            if (!string.IsNullOrEmpty(userAgent))
            {
                query["user_agent"] = userAgent;
            }
            if (!string.IsNullOrEmpty(headers))
            {
                query["headers"] = headers;
            }
            if (!string.IsNullOrEmpty(cookies))
            {
                query["cookies"] = cookies;
            }
            if (latitude != 0)
            {
                if (latitude < -90 || latitude > 90)
                {
                    throw new ArgumentOutOfRangeException(nameof(latitude), latitude, "Value must be between -90 and 90.");
                }
                query["latitude"] = latitude.ToString();
            }
            if (longitude != 0)
            {
                if (longitude < -180 || longitude > 180)
                {
                    throw new ArgumentOutOfRangeException(nameof(longitude), longitude, "Value must be between -180 and 180.");
                }
                query["longitude"] = longitude.ToString();
            }
            if (accuracy != 0)
            {
                query["accuracy"] = accuracy.ToString();
            }
            if (!string.IsNullOrEmpty(proxy)) // check valid
            {
                query["proxy"] = proxy;
            }

            string json;

            using (var wc = new WebClient())
            {
                json = await wc.DownloadStringTaskAsync($"{ApiEndpoint}?{query}");
            }
            return(JsonConvert.DeserializeObject <ApiFlashResponse>(json));
        }
Ejemplo n.º 24
0
        public static StreamInfo RetrievePreview(ResourceBE attachment, uint height, uint width, RatioType ratio, SizeType size, FormatType format, out string filename)
        {
            if (!AttachmentBL.Instance.IsAllowedForImageMagickPreview(attachment))
            {
                throw new AttachmentPreviewFailedWithMimeTypeNotImplementedException(attachment.MimeType);
            }
            if (format != FormatType.UNDEFINED && size != SizeType.UNDEFINED && size != SizeType.ORIGINAL && size != SizeType.CUSTOM)
            {
                throw new AttachmentPreviewFormatConversionWithSizeNotImplementedException();
            }

            // check that attachment has a width and height defined
            AttachmentBL.Instance.IdentifyUnknownImages(new ResourceBE[] { attachment });

            #region check validity of size, width, and height parameters

            // NOTE (steveb): following table describes the possible state-transitions; note that the resulting graph must acyclic to avoid infinite loops.
            //      BESTFIT
            //          -> THUMB
            //          -> WEBVIEW
            //          -> ORIGINAL
            //      UNDEFINED
            //          -> CUSTOM
            //          -> ORIGINAL
            //      THUMB
            //          -> ORIGINAL
            //      WEBVIEW
            //          -> ORIGINAL
            //      CUSTOM
            //          -> ORIGINAL
            //      ORIGINAL
again:
            switch (size)
            {
            case SizeType.BESTFIT:
                if (width == 0 && height == 0)
                {
                    // no dimensions specified, use original
                    size = SizeType.ORIGINAL;
                    goto again;
                }
                if (width <= DekiContext.Current.Instance.ImageThumbPixels && height <= DekiContext.Current.Instance.ImageThumbPixels)
                {
                    // thumbnail is big enough
                    size = SizeType.THUMB;
                    goto again;
                }
                else if (width <= DekiContext.Current.Instance.ImageWebviewPixels && height <= DekiContext.Current.Instance.ImageWebviewPixels)
                {
                    // webview is big enough
                    size = SizeType.WEBVIEW;
                    goto again;
                }
                else
                {
                    // use original
                    size = SizeType.ORIGINAL;
                    goto again;
                }

            case SizeType.CUSTOM:
                if (height == 0 && width == 0)
                {
                    // no dimensions specified, use original
                    size = SizeType.ORIGINAL;
                    goto again;
                }
                if ((attachment.MetaXml.ImageWidth <= width && attachment.MetaXml.ImageHeight <= height) && (attachment.MetaXml.ImageWidth >= 0 && attachment.MetaXml.ImageHeight >= 0))
                {
                    // requested dimensions are larger than original, use original (we don't scale up!)
                    size = SizeType.ORIGINAL;
                    goto again;
                }
                break;

            case SizeType.ORIGINAL:
                width  = 0;
                height = 0;
                break;

            case SizeType.UNDEFINED:
                if (height != 0 || width != 0)
                {
                    size = SizeType.CUSTOM;
                    goto again;
                }
                else
                {
                    size = SizeType.ORIGINAL;
                    goto again;
                }

            case SizeType.THUMB:
                width  = DekiContext.Current.Instance.ImageThumbPixels;
                height = DekiContext.Current.Instance.ImageThumbPixels;
                if ((attachment.MetaXml.ImageWidth <= width && attachment.MetaXml.ImageHeight <= height) && (attachment.MetaXml.ImageWidth >= 0 && attachment.MetaXml.ImageHeight >= 0))
                {
                    size = SizeType.ORIGINAL;
                    goto again;
                }
                break;

            case SizeType.WEBVIEW:
                width  = DekiContext.Current.Instance.ImageWebviewPixels;
                height = DekiContext.Current.Instance.ImageWebviewPixels;
                if ((attachment.MetaXml.ImageWidth <= width && attachment.MetaXml.ImageHeight <= height) && (attachment.MetaXml.ImageWidth >= 0 && attachment.MetaXml.ImageHeight >= 0))
                {
                    size = SizeType.ORIGINAL;
                    goto again;
                }
                break;
            }
            #endregion


            // Asking to convert to the same format as original
            if (format != FormatType.UNDEFINED && format == ResolvePreviewFormat(attachment.MimeType))
            {
                format = FormatType.UNDEFINED;
            }

            //Determine if the result is capable of being cached
            bool cachable = (
                format == FormatType.UNDEFINED &&                    //No format conversion
                ratio != RatioType.VARIABLE &&                       //must be a fixed aspect ratio or not provided
                (size == SizeType.THUMB || size == SizeType.WEBVIEW) //must be one of the known cached thumb sizes.
                );

            // load image
            StreamInfo result = null;
            try {
                if (size == SizeType.ORIGINAL && format == FormatType.UNDEFINED)
                {
                    result = DekiContext.Current.Instance.Storage.GetFile(attachment, SizeType.ORIGINAL, false);
                }
                else
                {
                    bool cached = false;

                    //The type of image is based on uploaded file's mimetype
                    if (format == FormatType.UNDEFINED)
                    {
                        format = ResolvePreviewFormat(attachment.MimeType);
                    }

                    // check if image can be taken from the cache
                    if (cachable)
                    {
                        result = GetCachedThumb(attachment, size);
                        cached = (result != null);
                    }

                    // load image if we haven't yet
                    if (result == null)
                    {
                        result = DekiContext.Current.Instance.Storage.GetFile(attachment, SizeType.ORIGINAL, false);
                        if (result != null)
                        {
                            result = BuildThumb(attachment, result, format, ratio, width, height);
                        }
                    }

                    // store result if possible and needed
                    if (cachable && !cached && (result != null))
                    {
                        SaveCachedThumb(attachment, size, result);
                        result = GetCachedThumb(attachment, size);
                    }
                }
                if (result == null)
                {
                    ThrowOnBadPreviewImage();
                }

                // full filename for response content-disposition header
                switch (size)
                {
                case SizeType.CUSTOM:
                    filename = string.Format("{0}_({1}x{2}){3}", attachment.Name, width == 0 ? "" : width.ToString(), height == 0 ? "" : height.ToString(), attachment.FilenameExtension == string.Empty ? string.Empty : "." + attachment.FilenameExtension);
                    break;

                case SizeType.ORIGINAL:
                    filename = attachment.Name;
                    break;

                case SizeType.BESTFIT:
                case SizeType.THUMB:
                case SizeType.UNDEFINED:
                case SizeType.WEBVIEW:
                default:
                    filename = string.Format("{0}_({1}){2}", attachment.Name, size.ToString().ToLowerInvariant(), attachment.FilenameExtension == string.Empty ? string.Empty : "." + attachment.FilenameExtension);
                    break;
                }
                if (format != FormatType.UNDEFINED)
                {
                    filename = Path.ChangeExtension(filename, format.ToString().ToLowerInvariant());
                }
                return(result);
            } catch {
                if (result != null)
                {
                    result.Close();
                }
                throw;
            }
        }
Ejemplo n.º 25
0
        public static StreamInfo RetrievePreview(ResourceBE attachment, uint height, uint width, RatioType ratio, SizeType size, FormatType format, out string filename) {
            if (!AttachmentBL.Instance.IsAllowedForImageMagickPreview(attachment)) {
                throw new AttachmentPreviewFailedWithMimeTypeNotImplementedException(attachment.MimeType);
            }
            if(format != FormatType.UNDEFINED && size != SizeType.UNDEFINED && size != SizeType.ORIGINAL && size != SizeType.CUSTOM) {
                throw new AttachmentPreviewFormatConversionWithSizeNotImplementedException();
            }

            // check that attachment has a width and height defined
            AttachmentBL.Instance.IdentifyUnknownImages(new ResourceBE[] { attachment });

            #region check validity of size, width, and height parameters

            // NOTE (steveb): following table describes the possible state-transitions; note that the resulting graph must acyclic to avoid infinite loops.
            //      BESTFIT
            //          -> THUMB
            //          -> WEBVIEW
            //          -> ORIGINAL
            //      UNDEFINED
            //          -> CUSTOM
            //          -> ORIGINAL
            //      THUMB
            //          -> ORIGINAL
            //      WEBVIEW
            //          -> ORIGINAL
            //      CUSTOM
            //          -> ORIGINAL
            //      ORIGINAL
        again:
            switch(size) {
            case SizeType.BESTFIT:
                if(width == 0 && height == 0) {

                    // no dimensions specified, use original
                    size = SizeType.ORIGINAL;
                    goto again;
                }
                if(width <= DekiContext.Current.Instance.ImageThumbPixels && height <= DekiContext.Current.Instance.ImageThumbPixels) {

                    // thumbnail is big enough
                    size = SizeType.THUMB;
                    goto again;
                } else if(width <= DekiContext.Current.Instance.ImageWebviewPixels && height <= DekiContext.Current.Instance.ImageWebviewPixels) {

                    // webview is big enough
                    size = SizeType.WEBVIEW;
                    goto again;
                } else {

                    // use original
                    size = SizeType.ORIGINAL;
                    goto again;
                }
            case SizeType.CUSTOM:
                if(height == 0 && width == 0) {

                    // no dimensions specified, use original
                    size = SizeType.ORIGINAL;
                    goto again;
                }
                if((attachment.MetaXml.ImageWidth <= width && attachment.MetaXml.ImageHeight <= height) && (attachment.MetaXml.ImageWidth >= 0 && attachment.MetaXml.ImageHeight >= 0)) {

                    // requested dimensions are larger than original, use original (we don't scale up!)
                    size = SizeType.ORIGINAL;
                    goto again;
                }
                break;
            case SizeType.ORIGINAL:
                width = 0;
                height = 0;
                break;
            case SizeType.UNDEFINED:
                if(height != 0 || width != 0) {
                    size = SizeType.CUSTOM;
                    goto again;
                } else {
                    size = SizeType.ORIGINAL;
                    goto again;
                }
            case SizeType.THUMB:
                width = DekiContext.Current.Instance.ImageThumbPixels;
                height = DekiContext.Current.Instance.ImageThumbPixels;
                if((attachment.MetaXml.ImageWidth <= width && attachment.MetaXml.ImageHeight <= height) && (attachment.MetaXml.ImageWidth >= 0 && attachment.MetaXml.ImageHeight >= 0)) {
                    size = SizeType.ORIGINAL;
                    goto again;
                }
                break;
            case SizeType.WEBVIEW:
                width = DekiContext.Current.Instance.ImageWebviewPixels;
                height = DekiContext.Current.Instance.ImageWebviewPixels;
                if((attachment.MetaXml.ImageWidth <= width && attachment.MetaXml.ImageHeight <= height) && (attachment.MetaXml.ImageWidth >= 0 && attachment.MetaXml.ImageHeight >= 0)) {
                    size = SizeType.ORIGINAL;
                    goto again;
                }
                break;
            }
            #endregion


            // Asking to convert to the same format as original
            if(format != FormatType.UNDEFINED && format == ResolvePreviewFormat(attachment.MimeType)) {
                format = FormatType.UNDEFINED;
            }

            //Determine if the result is capable of being cached
            bool cachable = (
                format == FormatType.UNDEFINED       //No format conversion
                && ratio != RatioType.VARIABLE       //must be a fixed aspect ratio or not provided
                && (size == SizeType.THUMB || size == SizeType.WEBVIEW)  //must be one of the known cached thumb sizes.
            );

            // load image
            StreamInfo result = null;
            try {
                if(size == SizeType.ORIGINAL && format == FormatType.UNDEFINED) {
                    result = DekiContext.Current.Instance.Storage.GetFile(attachment, SizeType.ORIGINAL, false);
                } else {
                    bool cached = false;

                    //The type of image is based on uploaded file's mimetype
                    if(format == FormatType.UNDEFINED) {
                        format = ResolvePreviewFormat(attachment.MimeType);
                    }

                    // check if image can be taken from the cache
                    if(cachable) {
                        result = GetCachedThumb(attachment, size);
                        cached = (result != null);
                    }

                    // load image if we haven't yet
                    if(result == null) {
                        result = DekiContext.Current.Instance.Storage.GetFile(attachment, SizeType.ORIGINAL, false);
                        if(result != null) {
                            result = BuildThumb(attachment, result, format, ratio, width, height);
                        }
                    }

                    // store result if possible and needed
                    if(cachable && !cached && (result != null)) {
                        SaveCachedThumb(attachment, size, result);
                        result = GetCachedThumb(attachment, size);
                    }
                }
                if(result == null) {
                    ThrowOnBadPreviewImage();
                }

                // full filename for response content-disposition header
                switch(size) {
                case SizeType.CUSTOM:
                    filename = string.Format("{0}_({1}x{2}){3}", attachment.Name, width == 0 ? "" : width.ToString(), height == 0 ? "" : height.ToString(), attachment.FilenameExtension == string.Empty ? string.Empty : "." + attachment.FilenameExtension);
                    break;
                case SizeType.ORIGINAL:
                    filename = attachment.Name;
                    break;
                case SizeType.BESTFIT:
                case SizeType.THUMB:
                case SizeType.UNDEFINED:
                case SizeType.WEBVIEW:
                default:
                    filename = string.Format("{0}_({1}){2}", attachment.Name, size.ToString().ToLowerInvariant(), attachment.FilenameExtension == string.Empty ? string.Empty : "." + attachment.FilenameExtension);
                    break;
                }
                if(format != FormatType.UNDEFINED) {
                    filename = Path.ChangeExtension(filename, format.ToString().ToLowerInvariant());
                }
                return result;
            } catch {
                if(result != null) {
                    result.Close();
                }
                throw;
            }
        }
Ejemplo n.º 26
0
 protected BaseFormat(FormatType format)
     : this(FormattingUtility.Library(format.ToString()))
 {
 }