Esempio n. 1
0
        public string GetOcr(string type, string fileName)
        {
            string querys = "";

            // string bodys = "{\"image\":\"图片二进制数据的base64编码或者图片url\"#图片以base64编码的string}";

            string base64 = getFileBase64(fileName);

            string bodys = "{\"image\":\"" + base64 + "\"" + "}";

            string url = "";

            switch (type)
            {
            case "名片":
                url = "https://dm-57.data.aliyun.com/rest/160601/ocr/ocr_business_card.json";
                break;

            case "车牌":
                url = "https://ocrcp.market.alicloudapi.com/rest/160601/ocr/ocr_vehicle_plate.json";
                break;

            default:
                return("");
            }

            HttpWebRequest  httpRequest  = null;
            HttpWebResponse httpResponse = null;

            if (0 < querys.Length)
            {
                url = url + "?" + querys;
            }

            if (url.Contains("https://"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
            }
            else
            {
                httpRequest = (HttpWebRequest)WebRequest.Create(url);
            }
            httpRequest.Method = method;
            httpRequest.Headers.Add("Authorization", "APPCODE " + appcode);
            //根据API的要求,定义相对应的Content-Type
            httpRequest.ContentType = "application/json; charset=UTF-8";
            if (0 < bodys.Length)
            {
                byte[] data = Encoding.UTF8.GetBytes(bodys);
                using (Stream stream = httpRequest.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            try
            {
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();
            }
            catch (WebException ex)
            {
                httpResponse = (HttpWebResponse)ex.Response;
            }

            Console.WriteLine(httpResponse.StatusCode);
            Console.WriteLine(httpResponse.Method);
            Console.WriteLine(httpResponse.Headers);
            Stream       st     = httpResponse.GetResponseStream();
            StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));

            return("阿里" + type + "识别:\r\n" + reader.ReadToEnd());
        }
Esempio n. 2
0
            /// <summary>
            ///
            /// </summary>
            /// <param name="url">目标路径</param>
            /// <param name="P">平台</param>
            /// <returns></returns>
            public bool 判断(string url, string P, string roomId)
            {
                try
                {
                    switch (P)
                    {
                    case "bilibili":
                    {
                        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
                        httpWebRequest.Accept    = "*/*";
                        httpWebRequest.UserAgent = MMPU.UA.Ver.UA();
                        httpWebRequest.Headers.Add("Accept-Language: zh-CN,zh;q=0.8,en;q=0.6,ja;q=0.4");
                        if (!string.IsNullOrEmpty(MMPU.Cookie))
                        {
                            httpWebRequest.Headers.Add("Cookie", MMPU.Cookie);
                        }
                        httpWebRequest.Timeout = 3000;
                        //返回响应状态是否是成功比较的布尔值

                        if (((HttpWebResponse)httpWebRequest.GetResponse()).StatusCode == HttpStatusCode.OK)
                        {
                        }
                        InfoLog.InfoPrintf("判断文件存在", InfoLog.InfoClass.杂项提示);
                        return(true);
                    }

                    case "主站视频":
                        return(true);

                    default:
                        return(false);
                    }
                }
                //catch (WebException e)
                //{
                //    if(e.Status== WebExceptionStatus.Timeout)
                //    {
                //        return true;
                //    }
                //    return false;

                //}
                catch (Exception)
                {
                    InfoLog.InfoPrintf("判断文件不存在", InfoLog.InfoClass.杂项提示);
                    return(false);
                    //if (E.Message.Contains("404"))
                    //{
                    //    InfoLog.InfoPrintf("判断文件不存在", InfoLog.InfoClass.杂项提示);
                    //    return false;
                    //}
                    //else if (E.Message.Contains("475"))
                    //{
                    //    InfoLog.InfoPrintf("判断文件不存在", InfoLog.InfoClass.杂项提示);
                    //    return false;
                    //}
                    //else
                    //{
                    //    return true;
                    //}
                }
            }
Esempio n. 3
0
        public static string HttpPost(string url, string cerPath, string certpwd, CookieContainer cookieContainer = null, Stream postStream = null, Dictionary <string, string> fileDictionary = null, string refererUrl = null, Encoding encoding = null)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            if (url.Contains("https"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);

                request = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
                if (certpwd != null)
                {
                    //加载证书
                    string     password   = certpwd;;
                    FileStream fileStream = new FileStream(cerPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                    byte[]     bytes      = new byte[fileStream.Length];
                    fileStream.Read(bytes, 0, bytes.Length);
                    fileStream.Close();
                    X509Certificate2 cert = new X509Certificate2(bytes, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
                    request.ClientCertificates.Add(cert);
                }
            }
            else
            {
                request = (HttpWebRequest)WebRequest.Create(url);
            }

            request.ServicePoint.Expect100Continue = false;
            request.KeepAlive     = true;
            request.UserAgent     = "Mall";
            request.Method        = "POST";
            request.Timeout       = 6000;
            request.ContentType   = "text/xml";
            request.ContentLength = postStream != null ? postStream.Length : 0;

            if (!string.IsNullOrEmpty(refererUrl))
            {
                request.Referer = refererUrl;
            }
            if (cookieContainer != null)
            {
                request.CookieContainer = cookieContainer;
            }
            #region 输入二进制流
            if (postStream != null)
            {
                postStream.Position = 0;
                Stream requestStream = null;
                if (url.ToLower().IndexOf("https") > -1)
                {
                    ServicePointManager.Expect100Continue = true;
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    request.ProtocolVersion = HttpVersion.Version10;
                }
                //直接写入流
                requestStream = request.GetRequestStream();
                byte[] buffer    = new byte[1024];
                int    bytesRead = 0;
                while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    requestStream.Write(buffer, 0, bytesRead);
                }

                postStream.Close();//关闭文件访问
            }
            #endregion
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (cookieContainer != null)
            {
                response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
            }

            using (Stream responseStream = response.GetResponseStream())
            {
                using (StreamReader myStreamReader = new StreamReader(responseStream, encoding ?? Encoding.GetEncoding("utf-8")))
                {
                    string retString = myStreamReader.ReadToEnd();
                    return(retString);
                }
            }
        }
Esempio n. 4
0
        public ActionResult PaymentComplete(string ID)
        {
            try
            {
                var IDInt = GenericLogic.GetInt(ID);

                if (!IDInt.HasValue)
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
                }

                var contrib = db.PledgeContributors.FirstOrDefault(c => c.ID == IDInt);

                if (contrib == null)
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
                }


                string url = ConfigurationManager.AppSettings["JustGivingAPIURL"] + ConfigurationManager.AppSettings["JustGivingAppId"] + "/v1/donation/ref/" + contrib.ID;

                //need to check this...contrib.ThirdPartyRef
                var i = new Uri(url);

                var request = WebRequest.CreateDefault(i);
                request.Method      = "GET";
                request.ContentType = "application/json";

                var          response      = request.GetResponse();
                StreamReader reader        = new StreamReader(response.GetResponseStream());
                var          requestedText = reader.ReadToEnd();


                dynamic data = System.Web.Helpers.Json.Decode(requestedText);


                // var amount = data?.donations[0]?.amount;
                var thirdPartyReference = data?.donations[0]?.thirdPartyReference;
                var status = data?.donations[0]?.status;//"Accepted"

                if (thirdPartyReference != contrib.ID.ToString())
                {
                    throw new Exception();
                }

                if (status == "Accepted")
                {
                    contrib.Status = PledgeContributors.PledgeContribuionStatus.Completed;
                    db.SaveChanges();
                }
                else
                {
                    Messaging.Add(Message.LevelEnum.alert_warning, "Looks like the payment wasn't made. Try making payment again.", Message.TypeEnum.TemporaryAlert, contrib.Sinner);
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }

                Messaging.Add(Message.LevelEnum.alert_success, "Thank You. Your payment has now been processed.", Message.TypeEnum.StickyAlert, contrib.Sinner);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            catch {
                if (CurrentUser() != null)
                {
                    Messaging.Add(Message.LevelEnum.alert_warning, "OOps! that didn't work. try making payment again.", Message.TypeEnum.TemporaryAlert, CurrentUser());
                    db.SaveChanges();
                }
                return(RedirectToAction("Index"));
            }
        }
Esempio n. 5
0
        /// <summary>
        /// WebClient上传文件至服务器
        /// </summary>
        /// <param name="fileNamePath">文件名,全路径格式</param
        /// <param name="uriString">服务器文件夹路径</param>
        /// <param name="IsAutoRename">是否自动按照时间重命名</param>
        public void UpLoadFile(string fileNamePath, string uriString, bool IsAutoRename)
        {
            NetworkCredential credentials = new NetworkCredential("Administrator", "Lxr+19850223");

            //判断是否存在文件夹,如果不存在,新建
            if (!Directory.Exists(uriString))
            {
                HttpWebRequest mywebRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(uriString));
                mywebRequest.Credentials = credentials;
                // mywebRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
                mywebRequest.Method = "MKD";

                try
                {
                    //FtpWebResponse response = mywebRequest.GetResponse() as FtpWebResponse;
                    HttpWebResponse response = mywebRequest.GetResponse() as HttpWebResponse;
                }
                catch { }
            }
            string fileName = fileNamePath.Substring(fileNamePath.LastIndexOf("\\") + 1);
            //上传的文件样式xxxxxxxxx_006.xlsx
            //string strVN = NewFileName.Substring(NewFileName.LastIndexOf("_") + 1);//"006.xlsx"
            //strVN.Substring(0, strVN.LastIndexOf("."));//006
            //NewFileName.Substring(0, NewFileName.LastIndexOf("_"))//xxxxxxxxx
            string NewFileName = fileName;

            if (IsAutoRename)
            {
                NewFileName = DateTime.Now.ToString("yyMMddhhmmss") + DateTime.Now.Millisecond.ToString() + fileNamePath.Substring(fileNamePath.LastIndexOf("."));
            }
            string fileNameExt = fileName.Substring(fileName.LastIndexOf(".") + 1);

            if (uriString.EndsWith("/") == false)
            {
                uriString = uriString + "/";
            }
            uriString = uriString + NewFileName;
            WebClient myWebClient = new WebClient();

            // myWebClient.Credentials = CredentialCache.DefaultCredentials;
            myWebClient.Credentials = credentials;
            FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
            //FileStream fs = OpenFile();
            BinaryReader r = new BinaryReader(fs);

            byte[] postArray  = r.ReadBytes((int)fs.Length);
            Stream postStream = myWebClient.OpenWrite(uriString, "PUT");

            try
            {
                //使用UploadFile方法可以用下面的格式
                //myWebClient.UploadFile(uriString,"PUT",fileNamePath);
                if (postStream.CanWrite)
                {
                    postStream.Write(postArray, 0, postArray.Length);
                    postStream.Close();
                    fs.Dispose();
                }
                else
                {
                    postStream.Close();
                    fs.Dispose();
                }
            }
            catch
            {
                postStream.Close();
                fs.Dispose();
            }
            finally
            {
                postStream.Close();
                fs.Dispose();
            }
        }
Esempio n. 6
0
 public void CreateDefault_NullRequestUri_ThrowsArgumentNullException()
 {
     Assert.Throws <ArgumentNullException>(() => WebRequest.CreateDefault(null));
 }
Esempio n. 7
0
        public override ResponseInfo Respond(RequestInfo requestInfo)
        {
            var result = new ResponseInfo();

            result.Success = false;
            if (requestInfo.Uri == null)
            {
                return(result);
            }

            lock (FailedConnections) {
                if (FailedConnections.Contains(requestInfo.Uri.AbsoluteUri))
                {
                    return(result);
                }
            }

            var webRequest = WebRequest.CreateDefault(requestInfo.Uri);

            System.Net.WebResponse webResponse = null;
            try {
                webResponse = webRequest.GetResponse();

                var contentLength  = webResponse.ContentLength;
                var responseStream = webResponse.GetResponseStream();

                if (contentLength > 0)
                {
                    int pos = 0;

                    result.Data = new byte[contentLength];

                    int bytesRead = 1;
                    while (pos < contentLength && bytesRead != 0)
                    {
                        bytesRead = responseStream.Read(result.Data, pos, (int)contentLength - pos);
                        pos      += bytesRead;
                    }

                    if (pos == contentLength)
                    {
                        result.Success = true;
                    }
                    else
                    {
                        result.Success = false;
                    }
                }
                else
                {
                    var stream        = new MemoryStream();
                    var bytesReceived = 1;
                    var totalReceived = 0;
                    var buff          = new byte[1024];
                    while (bytesReceived != 0)
                    {
                        bytesReceived  = responseStream.Read(buff, 0, buff.Length);
                        totalReceived += bytesReceived;
                        stream.Write(buff, 0, bytesReceived);
                    }
                    result.Data = new byte[stream.Length];
                    // GetBuffer gives back the whole buffer, that is more than stream.Lenght
                    Array.Copy(stream.GetBuffer(), 0, result.Data, 0, stream.Length);
                    stream.Close();
                    result.Success = true;
                }
                responseStream.Close();

                result.MimeType = webResponse.ContentType;
            } catch (WebException we) {
                result.Success = false;
                lock (FailedConnections) {
                    FailedConnections.Add(requestInfo.Uri.AbsoluteUri);
                }
            } finally {
                if (webResponse != null)
                {
                    webResponse.Close();
                }
            }
            return(result);
        }
Esempio n. 8
0
    public static string sPostUrl = "";    //pos地址

    public void Login(string _userid, string _password)
    {
        TransFormat objformat;

        //构建poscontent
        Hashtable ht = new Hashtable();

        ht.Add("user", _userid);
        ht.Add("password", _password);
        ht.Add("action", "check");
        ht.Add("module", "login");
        Des coder = new Des();
        //时间戳
        long myTS = 0L;
        //加密
        string connentEnCode = coder.EnCode(HashtableToJson(ht), out myTS);

        objformat.TS          = myTS + "";
        objformat.PostContent = connentEnCode;
        objformat.Post_extra  = "";

        string sRequesturl = PBuildRequestpara(objformat);

        //pos数据
Retry:
        HttpWebRequest request = (HttpWebRequest)WebRequest.CreateDefault(
            new Uri(sPostUrl));

        request.UserAgent = "fandian99 print tools";    //协议标头
        request.Timeout   = 5000;
        byte[] readbytes = Encoding.ASCII.GetBytes(sRequesturl);
        request.Method        = "POST";
        request.ContentType   = "application/x-www-form-urlencoded";
        request.ContentLength = readbytes.Length;
        string responseData = "";

        try
        {
            using (Stream reqStream = request.GetRequestStream())
            {
                reqStream.Write(readbytes, 0, readbytes.Length);
                reqStream.Close();
            }

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Unicode))
                {
                    responseData = reader.ReadToEnd().ToString();
                    //处理函数
                    using (StringReader xmlSR = new StringReader(responseData))
                    {
                        ds.ReadXml(xmlSR, XmlReadMode.InferTypedSchema);
                        if (ds.Tables.Count > 0)
                        {
                            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                            {
                                token = ds.Tables[0].Rows[0]["TOKEN"].ToString();
                                //用户ID
                                iID = ds.Tables[0].Rows[0]["userID"].ToString();
                                //收款员ID/登录人ID
                                iLoginID = ds.Tables[0].Rows[0]["LoginID"].ToString();
                            }
                        }
                    }
                }
            }
        }
        catch
        {
            if (System.Windows.Forms.MessageBox.Show("连接服务器失败,是否重试", "消息", System.Windows.Forms.MessageBoxButtons.RetryCancel) == System.Windows.Forms.DialogResult.Retry)
            {
                goto Retry;
            }
        }
        finally
        {
        }
    }
Esempio n. 9
0
        /// <summary>
        /// 将图片发送到API
        /// </summary>
        /// <returns>返回一个JObject对象方便解析</returns>
        public JObject StartCheck()
        {
            //API地址  http或https协议都可以
            String url = "https://dm-51.data.aliyun.com/rest/160601/ocr/ocr_idcard.json";
            //如果输入带有inputs, 设置为True,否则设为False
            bool is_old_format = false;
            //输入自己的AppCode
            String appcode = "";
            //传递方式为post
            String method = "POST";

            String querys = "";

            String base64 = System.Convert.ToBase64String(contentBytes);
            String bodys;

            if (is_old_format)
            {
                bodys = "{\"inputs\" :" +
                        "[{\"image\" :" +
                        "{\"dataType\" : 50," +
                        "\"dataValue\" :\"" + base64 + "\"" +
                        "}";
                if (config.Length > 0)
                {
                    bodys += ",\"configure\" :" +
                             "{\"dataType\" : 50," +
                             "\"dataValue\" : \"" + config + "\"}" +
                             "}";
                }
                bodys += "]}";
            }
            else
            {
                bodys = "{\"image\":\"" + base64 + "\"";
                if (config.Length > 0)
                {
                    bodys += ",\"configure\" :\"" + config + "\"";
                }
                bodys += "}";
            }
            HttpWebRequest  httpRequest  = null;
            HttpWebResponse httpResponse = null;

            if (0 < querys.Length)
            {
                url = url + "?" + querys;
            }

            if (url.Contains("https://"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
            }
            else
            {
                httpRequest = (HttpWebRequest)WebRequest.Create(url);
            }
            httpRequest.Method = method;
            httpRequest.Headers.Add("Authorization", "APPCODE " + appcode);
            //根据API的要求,定义相对应的Content-Type
            httpRequest.ContentType = "application/json; charset=UTF-8";
            if (0 < bodys.Length)
            {
                byte[] data = Encoding.UTF8.GetBytes(bodys);
                using (Stream stream = httpRequest.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            try
            {
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();
            }
            catch (WebException ex)
            {
                httpResponse = (HttpWebResponse)ex.Response;
            }

            if (httpResponse.StatusCode != HttpStatusCode.OK)
            {
                Console.WriteLine("http error code: " + httpResponse.StatusCode);
                Console.WriteLine("error in header: " + httpResponse.GetResponseHeader("X-Ca-Error-Message"));
                Console.WriteLine("error in body: ");
            }
            Stream       st     = httpResponse.GetResponseStream();  //获取信息流返还
            StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
            JObject      jo     = JObject.Parse(reader.ReadToEnd()); //JSON对象

            return(jo);
        }
Esempio n. 10
0
        /// <summary>
        /// 处理请求
        /// </summary>
        /// <param name="Para"></param>
        /// <returns></returns>
        public Config.ResultObj Service(Config.GetPara Para)
        {
            const String host    = "https://ali-deliver.showapi.com";
            const String path    = "/showapi_expInfo";
            const String method  = "GET";
            const String appcode = "42b6f1042f8945d78ca59be867a39f5a";

            Config.ResultObj ret = new Config.ResultObj();
            #region ##参数验证
            if (Para == null)
            {
                ret.showapi_res_code  = 4;
                ret.showapi_res_error = "缺少请求参数";
                return(ret);
            }
            if (string.IsNullOrWhiteSpace(Para.com))
            {
                ret.showapi_res_code  = 4;
                ret.showapi_res_error = "缺少快递公司参数";
                return(ret);
            }
            if (string.IsNullOrWhiteSpace(Para.nu))
            {
                ret.showapi_res_code  = 4;
                ret.showapi_res_error = "缺少快递单号参数参数";
                return(ret);
            }
            #endregion
            #region ###开始处理
            String          querys       = "nu=" + Para.nu + "&com=" + "auto";
            String          bodys        = "";
            String          url          = host + path;
            HttpWebRequest  httpRequest  = null;
            HttpWebResponse httpResponse = null;

            if (0 < querys.Length)
            {
                url = url + "?" + querys;
            }

            if (host.Contains("https://"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
            }
            else
            {
                httpRequest = (HttpWebRequest)WebRequest.Create(url);
            }
            httpRequest.Method = method;
            httpRequest.Headers.Add("Authorization", "APPCODE " + appcode);
            if (0 < bodys.Length)
            {
                byte[] data = Encoding.UTF8.GetBytes(bodys);
                using (Stream stream = httpRequest.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            try
            {
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();
            }
            catch (WebException ex)
            {
                httpResponse = (HttpWebResponse)ex.Response;
            }
            //Console.WriteLine(httpResponse.StatusCode);
            //Console.WriteLine(httpResponse.Method);
            //Console.WriteLine(httpResponse.Headers);
            Stream       st         = httpResponse.GetResponseStream();
            StreamReader reader     = new StreamReader(st, Encoding.GetEncoding("utf-8"));
            string       ResultJson = reader.ReadToEnd();
            Normal.WritLog("参数:" + JsonConvert.SerializeObject(Para));
            Normal.WritLog("查询返回:" + ResultJson);
            if (!string.IsNullOrWhiteSpace(ResultJson))
            {
                ret = JsonConvert.DeserializeObject <Config.ResultObj>(ResultJson);
            }
            else
            {
                ret.showapi_res_code = 4; ret.showapi_res_error = "暂无返回数据";
            }
            //Console.WriteLine(reader.ReadToEnd());
            //Console.WriteLine("\n");
            #endregion
            return(ret);
        }
        public void GetHttpFileAndWriteLocalReturnFilePath()
        {
            if (m_Url.StartsWith("http") == false)
            {
                m_Url = "http://" + m_Url;
            }

            resquest         = (HttpWebRequest)WebRequest.CreateDefault(new Uri(m_Url));
            resquest.Method  = "GET";
            resquest.Timeout = 20000;
            resquest.BeginGetResponse((ar) =>
            {
                try
                {
                    #region Get Response And Write Byte
                    HttpWebResponse response = (HttpWebResponse)resquest.EndGetResponse(ar);
                    Stream responseSrewam    = response.GetResponseStream(); //获得数据流

                    string _direPath = System.IO.Path.GetDirectoryName(m_FilePath);

                    if (File.Exists(m_FilePath))  //Delete previous File
                    {
                        File.Delete(m_FilePath);
                    }

                    //     Debug.Log("路径AS " + _direPath);
                    if (Directory.Exists(_direPath) == false)
                    {
                        Directory.CreateDirectory(_direPath);
                    }

                    FileStream fileStream = new FileStream(m_FilePath, FileMode.Create, FileAccess.Write);
                    byte[] bytes          = new byte[1024];
                    int readSize          = 0;
                    while ((readSize = responseSrewam.Read(bytes, 0, 1024)) > 0)
                    { //循环度流和写文件
                        fileStream.Write(bytes, 0, readSize);
                    }

                    fileStream.Flush();
                    fileStream.Close();

                    if (response != null && response.StatusCode == HttpStatusCode.OK)
                    {
                        //if (CacheHelper.GetInstance().CacheImageDic2.ContainsKey(m_Url) == false)
                        //    CacheHelper.GetInstance().CacheImageDic2.Add(m_Url, m_FilePath); //Save Record

                        --HttpDownLoadHelper.currentTaskCount;
                        if (m_HttpFinishDownHandle != null)
                        {
                            m_HttpFinishDownHandle(true, m_FilePath, response);
                        }
                    }
                    if (responseSrewam != null)
                    {
                        responseSrewam.Close();
                    }
                    #endregion
                }
                catch (Exception e)
                {
                    #region Try Again
                    Debug.Log(m_Url + "  DownLoad Fail Times  " + m_TryTime + "   " + e.ToString());
                    if (m_TryTime != 0)
                    {//Try 3 times
                        m_TryTime--;
                        GetHttpFileAndWriteLocalReturnFilePath();
                    }
                    else
                    {
                        --HttpDownLoadHelper.currentTaskCount;
                        if (m_HttpFinishDownHandle != null)
                        {
                            m_HttpFinishDownHandle(false, m_FilePath, null);
                        }
                    }//esle
                    #endregion
                }
                finally
                {
                    if (resquest != null && resquest.GetResponse() != null)
                    {
                        resquest.GetResponse().Close();
                    }
                }
            }, null); //开始异步请求
        }
Esempio n. 12
0
        public bool Start()
        {
            string host    = service.GetConfigValue("ComrmsHost").ConfigValue;
            string path    = "/query/comrms";
            string method  = "GET";
            string appcode = service.GetConfigValue("ComrmsAppCode").ConfigValue;

            string          querys       = "symbols=" + service.GetConfigValue("ComrmsQuerys").ConfigValue;
            string          bodys        = "";
            string          url          = host + path;
            HttpWebRequest  httpRequest  = null;
            HttpWebResponse httpResponse = null;

            if (0 < querys.Length)
            {
                url = url + "?" + querys;
            }

            if (host.Contains("https://"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
            }
            else
            {
                httpRequest = (HttpWebRequest)WebRequest.Create(url);
            }
            httpRequest.Method = method;
            httpRequest.Headers.Add("Authorization", "APPCODE " + appcode);
            if (0 < bodys.Length)
            {
                byte[] data = Encoding.UTF8.GetBytes(bodys);
                using (Stream stream = httpRequest.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            try
            {
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();
            }
            catch (WebException ex)
            {
                httpResponse = (HttpWebResponse)ex.Response;
            }

            Stream       st       = httpResponse.GetResponseStream();
            StreamReader reader   = new StreamReader(st, Encoding.GetEncoding("utf-8"));
            string       contract = reader.ReadToEnd();
            Comrms       comrms   = contract.ToObject <Comrms>();

            if (comrms.Code == 0)
            {
                foreach (Obj obj in comrms.Obj)
                {
                    ColRow cRow = new ColRow("Contract", "FS", obj.FS, false);
                    if (cRow.R_HasField)
                    {
                        cRow["Price"] = obj.P;
                        cRow["NV"]    = obj.NV;
                        cRow["V"]     = obj.V;
                        cRow["Time"]  = new DateTime(1970, 1, 1, 0, 0, 0).AddHours(8).AddSeconds(obj.Tick);
                        cRow["ZF"]    = obj.ZF;
                        cRow.Update();
                    }
                    else
                    {
                        cRow["Id"]           = Guid.NewGuid().ToString();
                        cRow["ContractName"] = obj.N;
                        if (string.IsNullOrEmpty(obj.C))
                        {
                            cRow["ContractCode"] = obj.FS;
                        }
                        else
                        {
                            cRow["ContractCode"] = obj.S + obj.C;
                        }
                        cRow["Price"] = obj.P;
                        cRow["NV"]    = obj.NV;
                        cRow["V"]     = obj.V;
                        cRow["M"]     = obj.M;
                        cRow["S"]     = obj.S;
                        cRow["C"]     = obj.C;
                        cRow["Time"]  = new DateTime(1970, 1, 1, 0, 0, 0).AddHours(8).AddSeconds(obj.Tick);
                        cRow["ZF"]    = obj.ZF;
                        cRow.Insert();
                    }
                }
            }
            return(true);
        }
Esempio n. 13
0
        /// <summary>
        /// Executes the actual download from an URL. Does not handle exceptions,
        /// but takes care of proper cleanup.
        /// </summary>
        /// <exception cref="NonBinaryFileException">This exception is thrown, if the resulting file is not of a binary type</exception>
        /// <exception cref="TargetPathInvalidException">This exception is thrown, if the resulting target path of an application is not valid</exception>
        /// <param name="job">The job to process</param>
        /// <param name="urlToRequest">URL from which should be downloaded</param>
        /// <returns>true, if a new update has been found and downloaded, false otherwise</returns>
        protected Status DoDownload(ApplicationJob job, Uri urlToRequest)
        {
            // Lower security policies
            try
            {
                ServicePointManager.CheckCertificateRevocationList = false;
            }
            catch (PlatformNotSupportedException)
            {
                // .NET bug under special circumstances
            }

            ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
            {
                return(true);
            };

            // If we want to download multiple files simultaneously
            // from the same server, we need to "remove" the connection limit.
            ServicePointManager.DefaultConnectionLimit = 50;

            job.Variables.ResetDownloadCount();

            WebRequest.RegisterPrefix("sf", new ScpWebRequestCreator());
            WebRequest.RegisterPrefix("httpx", new HttpxRequestCreator());

            WebRequest req = WebRequest.CreateDefault(urlToRequest);

            AddRequestToCancel(req);
            req.Timeout = Convert.ToInt32(Settings.GetValue("ConnectionTimeout", 10)) * 1000; // 10 seconds by default

            HttpWebRequest httpRequest = req as HttpWebRequest;

            if (httpRequest != null)
            {
                // Store cookies for future requests. Some sites
                // check for previously stored cookies before allowing to download.
                if (httpRequest.CookieContainer == null)
                {
                    httpRequest.CookieContainer = m_Cookies;
                }
                else
                {
                    httpRequest.CookieContainer.Add(m_Cookies.GetCookies(httpRequest.RequestUri));
                }

                // If we have an HTTP request, some sites may require a correct referer
                // for the download.
                // If there are variables defined (from which most likely the download link
                // or version is being extracted), we'll just use the first variable's URL as referer.
                // The user still has the option to set a custom referer.
                // Note: Some websites don't "like" certain referers
                if (!m_NoAutoReferer.Contains(GetBaseHost(req.RequestUri)))
                {
                    foreach (UrlVariable urlVar in job.Variables.Values)
                    {
                        httpRequest.Referer = urlVar.Url;
                        break;
                    }
                }

                if (!string.IsNullOrEmpty(job.HttpReferer))
                {
                    httpRequest.Referer = job.Variables.ReplaceAllInString(job.HttpReferer);
                }

                LogDialog.Log(job, "Using referer: " + (string.IsNullOrEmpty(httpRequest.Referer) ? "(none)" : httpRequest.Referer));
                httpRequest.UserAgent = (string.IsNullOrEmpty(job.UserAgent) ? WebClient.UserAgent : job.UserAgent);

                // PAD files may be compressed
                httpRequest.AutomaticDecompression = (DecompressionMethods.GZip | DecompressionMethods.Deflate);
            }

            using (WebResponse response = WebClient.GetResponse(req))
            {
                LogDialog.Log(job, "Server source file: " + req.RequestUri.AbsolutePath);

                // Occasionally, websites are not available and an error page is encountered
                // For the case that the content type is just plain wrong, ignore it if the size is higher than 500KB
                HttpWebResponse httpResponse = response as HttpWebResponse;
                if (httpResponse != null && response.ContentLength < 500000)
                {
                    if (response.ContentType.StartsWith("text/xml") || response.ContentType.StartsWith("application/xml"))
                    {
                        // If an XML file is served, maybe we have a PAD file
                        ApplicationJob padJob = ApplicationJob.ImportFromPad(httpResponse);
                        if (padJob != null)
                        {
                            job.CachedPadFileVersion = padJob.CachedPadFileVersion;
                            return(DoDownload(job, new Uri(padJob.FixedDownloadUrl)));
                        }
                    }
                    if (response.ContentType.StartsWith("text/html"))
                    {
                        throw NonBinaryFileException.Create(response.ContentType, httpResponse.StatusCode);
                    }
                }

                long fileSize = GetContentLength(response);
                if (fileSize == 0)
                {
                    throw new IOException("Source file on server is empty (ContentLength = 0).");
                }

                string targetFileName = job.GetTargetFile(response, urlToRequest.AbsoluteUri);

                LogDialog.Log(job, "Determined target file name: " + targetFileName);

                // Only download, if the file size or date has changed
                if (!ForceDownload && !job.RequiresDownload(response, targetFileName))
                {
                    // If file already exists (created by user),
                    // the download is not necessary. We still need to
                    // set the file name.
                    // If the file exists, but not at the target location
                    // (after renaming), do not reset the previous location.
                    if (File.Exists(targetFileName))
                    {
                        job.PreviousLocation = targetFileName;
                    }
                    job.Save();
                    return(Status.NoUpdate);
                }

                // Skip downloading!
                // Installing also requires a forced download
                if (!ForceDownload && !m_InstallUpdated && (m_OnlyCheck || (job.CheckForUpdatesOnly && !IgnoreCheckForUpdatesOnly)))
                {
                    LogDialog.Log(job, "Skipped downloading updates");
                    return(Status.UpdateAvailable);
                }

                // Execute: Default pre-update command
                string defaultPreCommand = Settings.GetValue("PreUpdateCommand", "") as string;
                // For starting external download managers: {preupdate-url}
                defaultPreCommand = UrlVariable.Replace(defaultPreCommand, "preupdate-url", urlToRequest.ToString());
                ScriptType defaultPreCommandType = Command.ConvertToScriptType(Settings.GetValue("PreUpdateCommandType", ScriptType.Batch.ToString()) as string);

                int exitCode = new Command(defaultPreCommand, defaultPreCommandType).Execute(job, targetFileName);
                if (exitCode == 1)
                {
                    LogDialog.Log(job, "Default pre-update command returned '1', download aborted");
                    throw new CommandErrorException();
                }
                else if (exitCode == 2)
                {
                    LogDialog.Log(job, "Default pre-update command returned '2', download skipped");
                    return(Status.UpdateAvailable);
                }

                // Execute: Application pre-update command
                exitCode = new Command(UrlVariable.Replace(job.ExecutePreCommand, "preupdate-url", urlToRequest.ToString()), job.ExecutePreCommandType).Execute(job, targetFileName);
                if (exitCode == 1)
                {
                    LogDialog.Log(job, "Pre-update command returned '1', download aborted");
                    throw new CommandErrorException();
                }
                else if (exitCode == 2)
                {
                    LogDialog.Log(job, "Pre-update command returned '2', download skipped");
                    return(Status.UpdateAvailable);
                }
                else if (exitCode == 3)
                {
                    LogDialog.Log(job, "Pre-update command returned '3', external download");
                    job.LastUpdated = DateTime.Now;
                    job.Save();
                    return(Status.UpdateSuccessful);
                }

                // Read all file contents to a temporary location
                string tmpLocation = Path.GetTempFileName();

                // Read contents from the web and put into file
                using (Stream sourceFile = response.GetResponseStream())
                {
                    using (FileStream targetFile = File.Create(tmpLocation))
                    {
                        long byteCount = 0;
                        int  readBytes = 0;
                        m_Size[job] = fileSize;

                        do
                        {
                            if (m_CancelUpdates)
                            {
                                break;
                            }

                            // Some adjustment for SCP download: Read only up to the max known bytes
                            int maxRead = (fileSize > 0) ? (int)Math.Min(fileSize - byteCount, 1024) : 1024;
                            if (maxRead == 0)
                            {
                                break;
                            }

                            byte[] buffer = new byte[maxRead];
                            readBytes = sourceFile.Read(buffer, 0, maxRead);
                            if (readBytes > 0)
                            {
                                targetFile.Write(buffer, 0, readBytes);
                            }
                            byteCount += readBytes;
                            OnProgressChanged(byteCount, fileSize, job);
                        } while (readBytes > 0);
                    }
                }

                if (m_CancelUpdates)
                {
                    m_Progress[job] = 0;
                    OnStatusChanged(job);
                    return(Status.Failure);
                }

                // If each version has a different file name (version number),
                // we might only want to keep one of them. Also, we might
                // want to free some space on the target location.
                if (job.DeletePreviousFile)
                {
                    PathEx.TryDeleteFiles(job.PreviousLocation);
                }

                try
                {
                    File.SetLastWriteTime(tmpLocation, ApplicationJob.GetLastModified(response));
                }
                catch (ArgumentException)
                {
                    // Invalid file date. Ignore and just use DateTime.Now
                }

                try
                {
                    FileInfo downloadedFileInfo = new FileInfo(tmpLocation);
                    job.LastFileSize = downloadedFileInfo.Length;
                    job.LastFileDate = downloadedFileInfo.LastWriteTime;
                }
                catch (Exception ex)
                {
                    LogDialog.Log(job, ex);
                }

                try
                {
                    // Before copying, we might have to create the directory
                    Directory.CreateDirectory(Path.GetDirectoryName(targetFileName));

                    // Copying might fail if variables have been replaced with bad values.
                    // However, we cannot rely on functions to clean up the path, since they
                    // might actually parse the path incorrectly and return an even worse path.
                    File.Copy(tmpLocation, targetFileName, true);
                }
                catch (ArgumentException)
                {
                    throw new TargetPathInvalidException(targetFileName);
                }
                catch (NotSupportedException)
                {
                    throw new TargetPathInvalidException(targetFileName);
                }

                File.Delete(tmpLocation);

                // At this point, the update is complete
                job.LastUpdated      = DateTime.Now;
                job.PreviousLocation = targetFileName;
            }

            job.Save();

            job.ExecutePostUpdateCommands();

            return(Status.UpdateSuccessful);
        }
Esempio n. 14
0
        /// <summary>
        ///     增加或修改银行卡
        /// </summary>
        /// <param name="view"></param>
        /// <returns></returns>
        public ServiceResult AddOrUpdateBankCard(ApiBankCardInput view)
        {
            //银行卡必须为数字不能以0开头
            var r = new Regex("^([1-9][0-9]*)$");

            if (!r.IsMatch(view.BankCardId))
            {
                return(ServiceResult.Failure("请正确输入银行卡号"));
            }

            if (view.BankCardId.Length < 10)
            {
                return(ServiceResult.Failure("请正确输入银行卡号"));
            }

            if (view.Type == 0)
            {
                return(ServiceResult.Failure("请选择银行类型"));
            }

            #region 使用阿里接口判断银行卡是否正确

            var checkUrl =
                $"https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo={view.BankCardId}&cardBinCheck=true";
            var             httpRequest  = (HttpWebRequest)WebRequest.CreateDefault(new Uri(checkUrl));
            HttpWebResponse httpResponse = null;

            try
            {
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();
            }
            catch (WebException ex)
            {
                httpResponse = (HttpWebResponse)ex.Response;
            }

            var st         = httpResponse.GetResponseStream();
            var reader     = new StreamReader(st, Encoding.GetEncoding("utf-8"));
            var readResult = reader.ReadToEnd();
            try
            {
                var aliResult = readResult.DeserializeJson <AliResult>();
                if (aliResult.Validated != "true")
                {
                    return(ServiceResult.Failure("请正确输入银行卡号"));
                }
            }
            catch (Exception e)
            {
                return(ServiceResult.Failure("请正确输入银行卡号"));
            }

            #endregion 使用阿里接口判断银行卡是否正确

            var bankCardList = Resolve <IBankCardService>().GetList(u => u.UserId == view.LoginUserId);
            if (bankCardList.Count >= 10)
            {
                return(ServiceResult.Failure("银行卡最多只可绑定十张"));
            }

            var model    = Resolve <IBankCardService>().GetSingle(u => u.Number == view.BankCardId);
            var bankCard = new BankCard
            {
                Number  = view.BankCardId,
                Address = view.Address,
                Name    = view.Name,
                Type    = view.Type,
                UserId  = view.LoginUserId,
                Id      = view.Id.ToObjectId()
            };

            if (model == null)
            {
                var result = Add(bankCard);
                if (!result)
                {
                    return(ServiceResult.Failed);
                }

                return(ServiceResult.Success);
            }

            return(ServiceResult.Failure("该银行卡已经绑定"));
        }
        private string ExecuteWebRequest(HttpMethod method, Uri uri, string parameters, string authHeader)
        {
            WebRequest request;

            if (method == HttpMethod.POST)
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(parameters);

                request             = WebRequest.CreateDefault(uri);
                request.Method      = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                //request.ContentType = "text/xml";
                request.ContentLength = byteArray.Length;

                if (!String.IsNullOrEmpty(parameters))
                {
                    Stream dataStream = request.GetRequestStream();
                    dataStream.Write(byteArray, 0, byteArray.Length);
                    dataStream.Close();
                }
            }
            else
            {
                request = WebRequest.CreateDefault(String.IsNullOrEmpty(parameters)
                            ? new Uri(uri.ToString())
                            : new Uri(uri + "?" + parameters));
            }

            //Add Headers
            if (!String.IsNullOrEmpty(authHeader))
            {
                request.Headers.Add(HttpRequestHeader.Authorization, authHeader);
            }

            try
            {
                using (WebResponse response = request.GetResponse())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        if (responseStream != null)
                        {
                            using (var responseReader = new StreamReader(responseStream))
                            {
                                return(responseReader.ReadToEnd());
                            }
                        }
                    }
                }
            }
            catch (WebException ex)
            {
                using (Stream responseStream = ex.Response.GetResponseStream())
                {
                    if (responseStream != null)
                    {
                        using (var responseReader = new StreamReader(responseStream))
                        {
                            Logger.ErrorFormat("WebResponse exception: {0}", responseReader.ReadToEnd());
                        }
                    }
                }
            }
            return(null);
        }
Esempio n. 16
0
        /// <summary>
        /// 银行卡4要素认证接口
        /// </summary>
        /// <param name="bankModel"></param>
        /// <returns></returns>
        public static RequestResult Bank4Authenticate(BankCardModel bankModel)
        {
            RequestResult result = new RequestResult()
            {
                retCode = ReqResultCode.failed,
                retMsg  = "认证请求失败"
            };

            #region 验证数据
            if (bankModel == null)
            {
                result.retMsg = "需验证的银行卡信息不能为空";
                return(result);
            }
            if (string.IsNullOrEmpty(bankModel.cardNo))
            {
                result.retMsg = "银行卡号不能为空";
                return(result);
            }
            if (string.IsNullOrEmpty(bankModel.idNo))
            {
                result.retMsg = "身份证号码不能为空";
                return(result);
            }
            if (string.IsNullOrEmpty(bankModel.name))
            {
                result.retMsg = "开户名不能为空";
                return(result);
            }
            if (string.IsNullOrEmpty(bankModel.phoneNo))
            {
                result.retMsg = "手机号不能为空";
                return(result);
            }
            #endregion
            HttpWebRequest  httpRequest  = null;
            HttpWebResponse httpResponse = null;
            try
            {
                string bodys = $"ReturnBankInfo={ReturnBankInfo}&cardNo={bankModel.cardNo}&idNo={bankModel.idNo}&name={bankModel.name}&phoneNo={bankModel.phoneNo}";
                if (aliBankcardUrl.Contains("https://"))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(aliBankcardUrl));
                }
                else
                {
                    httpRequest = (HttpWebRequest)WebRequest.Create(aliBankcardUrl);
                }
                httpRequest.Method = method;
                httpRequest.Headers.Add("Authorization", "APPCODE " + aliAppcode);
                //根据API的要求,定义相对应的Content-Type
                httpRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
                if (0 < bodys.Length)
                {
                    byte[] data = Encoding.UTF8.GetBytes(bodys);
                    using (Stream stream = httpRequest.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
                }
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                using (var responseStream = httpResponse.GetResponseStream())
                    using (var mstream = new MemoryStream())
                    {
                        responseStream.CopyTo(mstream);
                        string             message = Encoding.UTF8.GetString(mstream.ToArray());
                        BankCardAuthResult data    = JsonConvert.DeserializeObject <BankCardAuthResult>(message);
                        if (data != null && data.respCode == "0000")
                        {
                            result.retCode    = ReqResultCode.success;
                            result.objectData = data;
                            result.retMsg     = ErrorCode[data.respCode];
                        }
                        else
                        {
                            result.retCode    = ReqResultCode.failed;
                            result.objectData = data;
                            result.retMsg     = data == null?"": ErrorCode[data.respCode];
                        }
                    }
            }
            catch (Exception ex)
            {
                result.retCode = ReqResultCode.excetion;
                result.retMsg  = $"调用阿里云银行卡认证时发生异常:{ex.Message}";
            }

            return(result);
        }
Esempio n. 17
0
        private void DownloadImageFromUrl(string url, string filename)
        {
            Uri urlUri = null;

            try
            {
                urlUri = new Uri(url);
            }
            catch (Exception e)
            {
                OnDownloadFailed(null, e.Message);
                return;
            }
            var request = WebRequest.CreateDefault(urlUri);

            request.Timeout = 5000;

            var buffer = new byte[4096];

            string savedPath = Path.Combine(GlobalVariables.AppDataFolder, filename);

            try
            {
                //using (var target = new FileStream(savedPath, FileMode.Create, FileAccess.Write))
                //{
                using (var response = request.GetResponse())
                {
                    using (var stream = response.GetResponseStream())
                    {
                        using (var mStream = new MemoryStream())
                        {
                            int read;
                            Debug.Assert(stream != null, "stream is null");
                            while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                //target.Write(buffer, 0, read);
                                mStream.Write(buffer, 0, read);
                            }

                            File.WriteAllBytes(savedPath, mStream.ToArray());

                            mStream.Position = 0;
                            var bitmapImage = new BitmapImage();
                            bitmapImage.BeginInit();
                            bitmapImage.StreamSource = mStream;
                            bitmapImage.CacheOption  = BitmapCacheOption.OnLoad;
                            bitmapImage.EndInit();

                            bitmapImage.Freeze();

                            GlobalVariables.ImageDictionary.Add(url, bitmapImage);

                            OnDownloadCompleted(bitmapImage);
                        }
                    }
                }
                //}
            }
            catch (Exception e)
            {
                OnDownloadFailed(null, e.Message);
            }
        }
Esempio n. 18
0
        public static CustomJsonResult Send(string template, string smsparam, string mobile)
        {
            LumosDbContext currentDb = new LumosDbContext();

            SysSmsSendHistory sendHistory = new SysSmsSendHistory();

            sendHistory.ApiName        = "sms.market.alicloudapi.com";
            sendHistory.TemplateParams = smsparam;
            sendHistory.TemplateCode   = template;
            sendHistory.Phone          = mobile;
            sendHistory.Creator        = "0";
            sendHistory.CreateTime     = DateTime.Now;

            CustomJsonResult result = new CustomJsonResult();


            try
            {
                String querys = string.Format("ParamString={1}&RecNum={2}&SignName={3}&TemplateCode={0}", template, UrlEncode(smsparam), mobile, "收款易");

                String          bodys        = "";
                String          url          = host + path;
                HttpWebRequest  httpRequest  = null;
                HttpWebResponse httpResponse = null;

                if (0 < querys.Length)
                {
                    url = url + "?" + querys;
                }

                if (host.Contains("https://"))
                {
                    httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
                }
                else
                {
                    httpRequest = (HttpWebRequest)WebRequest.Create(url);
                }
                httpRequest.Method = method;
                httpRequest.Headers.Add("Authorization", "APPCODE " + appcode);
                if (0 < bodys.Length)
                {
                    byte[] data = Encoding.UTF8.GetBytes(bodys);
                    using (Stream stream = httpRequest.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
                }

                httpResponse = (HttpWebResponse)httpRequest.GetResponse();

                Stream       st     = httpResponse.GetResponseStream();
                StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));

                string r = reader.ReadToEnd();


                AliCloudApiResult apiResult = Newtonsoft.Json.JsonConvert.DeserializeObject <AliCloudApiResult>(r);

                if (apiResult.Success)
                {
                    sendHistory.Result = Enumeration.SysSmsSendResult.Success;
                    currentDb.SysSmsSendHistory.Add(sendHistory);
                    currentDb.SaveChanges();


                    result = new CustomJsonResult(ResultType.Success, "发送成功");
                }
                else
                {
                    sendHistory.Result        = Enumeration.SysSmsSendResult.Failure;
                    sendHistory.FailureReason = string.Format("描述:{0}", apiResult.Message);
                    currentDb.SysSmsSendHistory.Add(sendHistory);
                    currentDb.SaveChanges();

                    LogUtil.Error(string.Format("调用短信{0}接口-错误信息:{1}", sendHistory.ApiName, apiResult.Message));

                    result = new CustomJsonResult(ResultType.Failure, "发送失败");
                }


                return(result);
            }
            catch (Exception ex)
            {
                sendHistory.Result = Enumeration.SysSmsSendResult.Exception;

                sendHistory.FailureReason = ex.Message;

                currentDb.SysSmsSendHistory.Add(sendHistory);
                currentDb.SaveChanges();

                LogUtil.Error(string.Format("调用短信{0}接口-错误信息:{1},描述:{2}", sendHistory.ApiName, ex.Message, ex.StackTrace));

                return(new CustomJsonResult(ResultType.Failure, "发送失败"));
            }
        }
Esempio n. 19
0
        protected override void Execute(CodeActivityContext context)
        {
            string   fileName = FileName.Get(context);
            string   appcode  = AppCode.Get(context);
            string   base64   = ImageToBase64String(fileName);
            FileInfo fileInfo = new FileInfo(fileName);

            //限制图片大小
            if (fileInfo.Length > 1204 * 1204 * 4)
            {
                throw new Exception("文件不能大于4M");
            }
            //调用阿里云地址:https://ocrapi-document.taobao.com/ocrservice/document
            string          host         = "https://ocrapi-document.taobao.com";
            string          path         = "/ocrservice/document";
            string          method       = "POST";
            string          querys       = "";
            string          bodys        = "{\"img\":\"" + base64 + "\",\"url\":\"\",\"prob\":" + probability.ToString().ToLower() + "\"}";
            string          url          = host + path;
            HttpWebRequest  httpRequest  = null;
            HttpWebResponse httpResponse = null;

            if (0 < querys.Length)
            {
                url = url + "?" + querys;
            }
            if (host.Contains("https://"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
            }
            else
            {
                httpRequest = (HttpWebRequest)WebRequest.Create(url);
            }
            httpRequest.Method = method;
            httpRequest.Headers.Add("Authorization", "APPCODE " + appcode);
            //根据API的要求,定义相对应的Content-Type
            httpRequest.ContentType = "application/json; charset=UTF-8";
            if (0 < bodys.Length)
            {
                byte[] data = Encoding.UTF8.GetBytes(bodys);
                using (Stream stream = httpRequest.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            try
            {
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();
            }
            catch (WebException ex)
            {
                httpResponse = (HttpWebResponse)ex.Response;
            }
            Stream       st          = httpResponse.GetResponseStream();
            StreamReader reader      = new StreamReader(st, Encoding.GetEncoding("utf-8"));
            string       responseStr = reader.ReadToEnd();

            Result.Set(context, responseStr);
            //OcrResult ocrResult = JsonConvert.DeserializeObject<OcrResult>(responseStr);
            //string text = OcrResultToString(ocrResult);
            //Result.Set(context, text);
        }
Esempio n. 20
0
        /// <summary>
        /// Register well-known schemes: 'http', 'file', 'string'(null).
        /// <para>
        ///
        /// Example: Recursively resolve the path from a Settings store.
        ///
        /// StreamFactory::Register("setting", ((path, args) =>
        ///		{
        ///		Stream result = null;
        ///		string sectionName = Path.GetDirectoryName(path);
        ///		string key = Path.GetFileName(path);
        ///
        ///		TDataStoreAdapter adapter = new TDataStoreAdapter();
        ///		IKeyedDataStore settings = new KeyedDataStore(adapter);
        ///
        ///		if (key != null && key.Length > 0)
        ///			result = StreamFactory::Create(settings[key], args);
        ///		return result;
        ///		}));
        ///
        /// </para>
        /// </summary>
        static StreamFactory()
        {
            try
            {
                //----------------------------------------------------------
                // Register some well-known schemes

                // Text is simply the path itself. Return a buffer over
                // the content.
                Register("string", ((path, args) =>
                {
                    Stream result;
                    StringReader reader = new StringReader(path);
                    UTF8Encoding encoder = new UTF8Encoding();
                    byte[] buffer = encoder.GetBytes(path);
                    result = new MemoryStream(buffer);
                    return(result);
                }));

                // Create a Stream from the response stream of an web-resource
                Register("http", ((path, args) =>
                {
                    Stream result = null;
                    Uri uri = new Uri("http://" + path);
                    WebRequest request = WebRequest.CreateDefault(uri);
                    using (WebResponse response = request.GetResponse())
                    {
                        // Make a copy of the contents of the response stream. The Response object
                        // and it's stream will be closed upon exiting the using-block, and any
                        // attempt to read it will result in System.Net.WebException.
                        result = new MemoryStream();
                        response.GetResponseStream().CopyTo(result);
                        result.Position = 0;
                    }
                    return(result);
                }));

                //-----------------------------------------------------------
                // Contents are stored in a file. The path will either be
                // rooted or releative. IN the rooted case, in which case
                // we just use the spath to open the file.
                // In the 2nd case we look relative to the
                // base directory of the running module.
                //-----------------------------------------------------------
                Register("file", ((path, args) =>
                {
                    Stream result;
                    // Use the current directory as the root of the file's path.
                    string baseDir = null;
                    path = String.Format(path, DateTime.Now);
                    if (!Path.IsPathRooted(path))
                    {
                        Process process = Process.GetCurrentProcess();
                        ProcessModule module = process.MainModule;
                        baseDir = Path.GetDirectoryName(module.FileName);
                        path = String.Format(@"{0}\{1}", baseDir, path);
                    }

                    baseDir = Path.GetDirectoryName(path);
                    if (!Directory.Exists(baseDir))
                    {
                        Directory.CreateDirectory(baseDir);
                    }

                    // Parse File Access parameters out of argument list.
                    Func <object[], Type, object> argParser =
                        ((al, type) =>
                    {
                        if (al != null && al.Length > 0)
                        {
                            return((from fm in al where fm.GetType() == type select fm).First());
                        }
                        return(null);
                    });



                    FileMode fileMode = (FileMode)(argParser(args, typeof(FileMode)) ?? FileMode.Open);
                    FileAccess fileAccess = (FileAccess)(argParser(args, typeof(FileMode)) ?? FileAccess.Read);
                    FileShare fileShare = (FileShare)(argParser(args, typeof(FileMode)) ?? FileShare.Read);
                    result = File.Open(path, fileMode, fileAccess, fileShare);
                    Debug.WriteLine(string.Format("StreamFactory {0}: 'file://{1}'",
                                                  fileMode,
                                                  path));

                    return(result);
                }));

                const string schemeTemplate = @"(?: (?<scheme> \w+ ) :(?: //)?)?" +
                                              "(?<path> .*)";
                _pathParser = new Regex(schemeTemplate,
                                        RegexOptions.IgnorePatternWhitespace
                                        | RegexOptions.IgnoreCase);
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.ToString());
                throw;
            }
        }
Esempio n. 21
0
        private void timer2_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (DateTime.Now.Minute == 0)
            {
                //取得一小时内分钟数据
                List <MinuteData> minuteDatas = GetMinuteDatas();
                if (minuteDatas.Count == 0)
                {
                    return;
                }
                //获取监测点污染物
                List <MonitorPointPollutan> monitorPointPollutans = GetMonitorPointPollutans();
                //用于数据库中一小时浓度的添加

                List <HourData> hourDatas = new List <HourData>();
                //用于求一小时的AQI

                List <AvgData> avgDatas = new List <AvgData>();
                DateTime       dateTime = DateTime.Now;
                //循环遍历除AQI之外的监测点污染物
                foreach (MonitorPointPollutan monitorPointPollutan in monitorPointPollutans.Where(m => m.PollutantId != 11))
                {
                    HourData hourData      = new HourData();
                    AvgData  avgData       = new AvgData();
                    var      mpMinuteDatas = minuteDatas.Where(m => m.Monitor_PollutionId == monitorPointPollutan.Id);

                    hourData.Monitor_PollutionId = monitorPointPollutan.Id;
                    hourData.MaxValue            = mpMinuteDatas.Max(m => m.AVGValue);
                    hourData.MinValue            = mpMinuteDatas.Min(m => m.AVGValue);
                    hourData.AVGValue            = mpMinuteDatas.Average(m => m.AVGValue);
                    hourData.MonitorTime         = dateTime;
                    hourDatas.Add(hourData);

                    avgData.AvgValue    = mpMinuteDatas.Average(m => m.AVGValue);
                    avgData.PointID     = monitorPointPollutan.PointId;
                    avgData.PollutantID = monitorPointPollutan.PollutantId;
                    avgDatas.Add(avgData);
                }
                AQICompute aqiCompute = new AQICompute();
                foreach (MonitorPointPollutan monitorPointPollutan in monitorPointPollutans.Where(m => m.PollutantId == 11))
                {
                    HourData hourData = new HourData();
                    hourData.Monitor_PollutionId = monitorPointPollutan.Id;
                    hourData.MonitorTime         = dateTime;
                    decimal pm2  = 0;
                    decimal pm10 = 0;
                    decimal co   = 0;
                    decimal no2  = 0;
                    decimal o3   = 0;
                    decimal so2  = 0;
                    foreach (AvgData avgData in avgDatas)
                    {
                        if (avgData.PointID == monitorPointPollutan.PointId)
                        {
                            switch (avgData.PollutantID)
                            {
                            case 12: pm2 = avgData.AvgValue; break;

                            case 13: co = avgData.AvgValue; break;

                            case 14: no2 = avgData.AvgValue; break;

                            case 15: o3 = avgData.AvgValue; break;

                            case 16: so2 = avgData.AvgValue; break;

                            case 17: pm10 = avgData.AvgValue; break;
                            }
                        }
                    }
                    hourData.AVGValue = Convert.ToDecimal(aqiCompute.GetAQI(pm2, co, no2, o3, so2, pm10));
                    hourDatas.Add(hourData);
                }
                #region 国控站
                string        stations = "[{\"city\":\"北京市\",\"city_code\":\"110000\",\"station\":\"万寿西宫\",\"station_code\":\"1001A\",\"lng\":116.366,\"lat\":39.8673},{\"city\":\"北京市\",\"city_code\":\"110000\",\"station\":\"定陵\",\"station_code\":\"1002A\",\"lng\":116.17,\"lat\":40.2865},{\"city\":\"北京市\",\"city_code\":\"110000\",\"station\":\"东四\",\"station_code\":\"1003A\",\"lng\":116.434,\"lat\":39.9522},{\"city\":\"北京市\",\"city_code\":\"110000\",\"station\":\"天坛\",\"station_code\":\"1004A\",\"lng\":116.434,\"lat\":39.8745},{\"city\":\"北京市\",\"city_code\":\"110000\",\"station\":\"农展馆\",\"station_code\":\"1005A\",\"lng\":116.473,\"lat\":39.9716},{\"city\":\"北京市\",\"city_code\":\"110000\",\"station\":\"官园\",\"station_code\":\"1006A\",\"lng\":116.361,\"lat\":39.9425},{\"city\":\"北京市\",\"city_code\":\"110000\",\"station\":\"海淀区万柳\",\"station_code\":\"1007A\",\"lng\":116.315,\"lat\":39.9934},{\"city\":\"北京市\",\"city_code\":\"110000\",\"station\":\"顺义新城\",\"station_code\":\"1008A\",\"lng\":116.72,\"lat\":40.1438},{\"city\":\"北京市\",\"city_code\":\"110000\",\"station\":\"怀柔镇\",\"station_code\":\"1009A\",\"lng\":116.644,\"lat\":40.3937},{\"city\":\"北京市\",\"city_code\":\"110000\",\"station\":\"昌平镇\",\"station_code\":\"1010A\",\"lng\":116.23,\"lat\":40.1952},{\"city\":\"北京市\",\"city_code\":\"110000\",\"station\":\"奥体中心\",\"station_code\":\"1011A\",\"lng\":116.407,\"lat\":40.0031},{\"city\":\"北京市\",\"city_code\":\"110000\",\"station\":\"古城\",\"station_code\":\"1012A\",\"lng\":116.225,\"lat\":39.9279},{\"city\":\"天津市\",\"city_code\":\"120000\",\"station\":\"勤俭道\",\"station_code\":\"1015A\",\"lng\":117.145,\"lat\":39.1654},{\"city\":\"天津市\",\"city_code\":\"120000\",\"station\":\"大直沽八号路\",\"station_code\":\"1017A\",\"lng\":117.237,\"lat\":39.1082},{\"city\":\"天津市\",\"city_code\":\"120000\",\"station\":\"前进道\",\"station_code\":\"1018A\",\"lng\":117.202,\"lat\":39.0927},{\"city\":\"天津市\",\"city_code\":\"120000\",\"station\":\"淮河道\",\"station_code\":\"1019A\",\"lng\":117.1837,\"lat\":39.2133},{\"city\":\"天津市\",\"city_code\":\"120000\",\"station\":\"跃进路\",\"station_code\":\"1021A\",\"lng\":117.307,\"lat\":39.0877},{\"city\":\"天津市\",\"city_code\":\"120000\",\"station\":\"第四大街\",\"station_code\":\"1023A\",\"lng\":117.707,\"lat\":39.0343},{\"city\":\"天津市\",\"city_code\":\"120000\",\"station\":\"永明路\",\"station_code\":\"1024A\",\"lng\":117.457,\"lat\":38.8394},{\"city\":\"天津市\",\"city_code\":\"120000\",\"station\":\"汉北路\",\"station_code\":\"1026A\",\"lng\":117.764,\"lat\":39.1587},{\"city\":\"天津市\",\"city_code\":\"120000\",\"station\":\"团泊洼\",\"station_code\":\"1027A\",\"lng\":117.157,\"lat\":38.9194},{\"city\":\"天津市\",\"city_code\":\"120000\",\"station\":\"河西一经路\",\"station_code\":\"2858A\",\"lng\":117.7918,\"lat\":39.2474},{\"city\":\"天津市\",\"city_code\":\"120000\",\"station\":\"津沽路\",\"station_code\":\"2859A\",\"lng\":117.3747,\"lat\":38.9846},{\"city\":\"天津市\",\"city_code\":\"120000\",\"station\":\"宾水西道\",\"station_code\":\"2860A\",\"lng\":117.1589,\"lat\":39.0845},{\"city\":\"天津市\",\"city_code\":\"120000\",\"station\":\"大理道\",\"station_code\":\"2922A\",\"lng\":117.1941,\"lat\":39.1067},{\"city\":\"天津市\",\"city_code\":\"120000\",\"station\":\"中山北路\",\"station_code\":\"3020A\",\"lng\":117.2099,\"lat\":39.16969},{\"city\":\"天津市\",\"city_code\":\"120000\",\"station\":\"西四道\",\"station_code\":\"3051A\",\"lng\":117.3916,\"lat\":39.1495},{\"city\":\"石家庄市\",\"city_code\":\"130100\",\"station\":\"职工医院\",\"station_code\":\"1029A\",\"lng\":114.4548,\"lat\":38.0513},{\"city\":\"石家庄市\",\"city_code\":\"130100\",\"station\":\"高新区\",\"station_code\":\"1030A\",\"lng\":114.6046,\"lat\":38.0398},{\"city\":\"石家庄市\",\"city_code\":\"130100\",\"station\":\"西北水源\",\"station_code\":\"1031A\",\"lng\":114.5019,\"lat\":38.1398},{\"city\":\"石家庄市\",\"city_code\":\"130100\",\"station\":\"西南高教\",\"station_code\":\"1032A\",\"lng\":114.4586111,\"lat\":38.00583333},{\"city\":\"石家庄市\",\"city_code\":\"130100\",\"station\":\"世纪公园\",\"station_code\":\"1033A\",\"lng\":114.5330556,\"lat\":38.01777778},{\"city\":\"石家庄市\",\"city_code\":\"130100\",\"station\":\"人民会堂\",\"station_code\":\"1034A\",\"lng\":114.5214,\"lat\":38.0524},{\"city\":\"石家庄市\",\"city_code\":\"130100\",\"station\":\"封龙山\",\"station_code\":\"1035A\",\"lng\":114.3541,\"lat\":37.9097},{\"city\":\"石家庄市\",\"city_code\":\"130100\",\"station\":\"22中南校区\",\"station_code\":\"2862A\",\"lng\":114.5480556,\"lat\":38.03777778},{\"city\":\"唐山市\",\"city_code\":\"130200\",\"station\":\"供销社\",\"station_code\":\"1036A\",\"lng\":118.1662,\"lat\":39.6308},{\"city\":\"唐山市\",\"city_code\":\"130200\",\"station\":\"雷达站\",\"station_code\":\"1037A\",\"lng\":118.144,\"lat\":39.643},{\"city\":\"唐山市\",\"city_code\":\"130200\",\"station\":\"物资局\",\"station_code\":\"1038A\",\"lng\":118.1853,\"lat\":39.6407},{\"city\":\"唐山市\",\"city_code\":\"130200\",\"station\":\"陶瓷公司\",\"station_code\":\"1039A\",\"lng\":118.2185,\"lat\":39.6679},{\"city\":\"唐山市\",\"city_code\":\"130200\",\"station\":\"十二中\",\"station_code\":\"1040A\",\"lng\":118.1838,\"lat\":39.65782},{\"city\":\"唐山市\",\"city_code\":\"130200\",\"station\":\"小山\",\"station_code\":\"1041A\",\"lng\":118.1997,\"lat\":39.6295},{\"city\":\"秦皇岛市\",\"city_code\":\"130300\",\"station\":\"北戴河环保局\",\"station_code\":\"1042A\",\"lng\":119.5259,\"lat\":39.8283},{\"city\":\"秦皇岛市\",\"city_code\":\"130300\",\"station\":\"第一关\",\"station_code\":\"1043A\",\"lng\":119.7624,\"lat\":40.0181},{\"city\":\"秦皇岛市\",\"city_code\":\"130300\",\"station\":\"监测站\",\"station_code\":\"1044A\",\"lng\":119.6023,\"lat\":39.9567},{\"city\":\"秦皇岛市\",\"city_code\":\"130300\",\"station\":\"建设大厦\",\"station_code\":\"1046A\",\"lng\":119.5369,\"lat\":39.9419},{\"city\":\"秦皇岛市\",\"city_code\":\"130300\",\"station\":\"文明里(启用171012)\",\"station_code\":\"3132A\",\"lng\":119.5967,\"lat\":37.0308},{\"city\":\"邯郸市\",\"city_code\":\"130400\",\"station\":\"环保局\",\"station_code\":\"1047A\",\"lng\":114.5129,\"lat\":36.61763},{\"city\":\"邯郸市\",\"city_code\":\"130400\",\"station\":\"东污水处理厂\",\"station_code\":\"1048A\",\"lng\":114.5426,\"lat\":36.6164},{\"city\":\"邯郸市\",\"city_code\":\"130400\",\"station\":\"矿院\",\"station_code\":\"1049A\",\"lng\":114.5035,\"lat\":36.5776},{\"city\":\"邯郸市\",\"city_code\":\"130400\",\"station\":\"丛台公园\",\"station_code\":\"1050A\",\"lng\":114.4965,\"lat\":36.61981},{\"city\":\"邢台市\",\"city_code\":\"130500\",\"station\":\"达活泉\",\"station_code\":\"1077A\",\"lng\":114.4821,\"lat\":37.0967},{\"city\":\"邢台市\",\"city_code\":\"130500\",\"station\":\"邢师高专\",\"station_code\":\"1078A\",\"lng\":114.5261,\"lat\":37.0533},{\"city\":\"邢台市\",\"city_code\":\"130500\",\"station\":\"路桥公司\",\"station_code\":\"1079A\",\"lng\":114.5331,\"lat\":37.0964},{\"city\":\"邢台市\",\"city_code\":\"130500\",\"station\":\"市环保局\",\"station_code\":\"1080A\",\"lng\":114.4854,\"lat\":37.062},{\"city\":\"保定市\",\"city_code\":\"130600\",\"station\":\"游泳馆\",\"station_code\":\"1051A\",\"lng\":115.493,\"lat\":38.8632},{\"city\":\"保定市\",\"city_code\":\"130600\",\"station\":\"华电二区\",\"station_code\":\"1052A\",\"lng\":115.5223,\"lat\":38.8957},{\"city\":\"保定市\",\"city_code\":\"130600\",\"station\":\"接待中心\",\"station_code\":\"1053A\",\"lng\":115.4713,\"lat\":38.9108},{\"city\":\"保定市\",\"city_code\":\"130600\",\"station\":\"地表水厂\",\"station_code\":\"1054A\",\"lng\":115.4612,\"lat\":38.8416},{\"city\":\"保定市\",\"city_code\":\"130600\",\"station\":\"胶片厂\",\"station_code\":\"1055A\",\"lng\":115.442,\"lat\":38.8756},{\"city\":\"承德市\",\"city_code\":\"130800\",\"station\":\"铁路\",\"station_code\":\"1062A\",\"lng\":117.9664,\"lat\":40.9161},{\"city\":\"承德市\",\"city_code\":\"130800\",\"station\":\"中国银行\",\"station_code\":\"1063A\",\"lng\":117.9525,\"lat\":40.9843},{\"city\":\"承德市\",\"city_code\":\"130800\",\"station\":\"开发区\",\"station_code\":\"1064A\",\"lng\":117.963,\"lat\":40.9359},{\"city\":\"承德市\",\"city_code\":\"130800\",\"station\":\"文化中心\",\"station_code\":\"1065A\",\"lng\":117.8184,\"lat\":40.9733},{\"city\":\"承德市\",\"city_code\":\"130800\",\"station\":\"离宫\",\"station_code\":\"1066A\",\"lng\":117.9384,\"lat\":41.0112},{\"city\":\"沧州市\",\"city_code\":\"130900\",\"station\":\"沧县城建局\",\"station_code\":\"1071A\",\"lng\":116.8854,\"lat\":38.2991},{\"city\":\"沧州市\",\"city_code\":\"130900\",\"station\":\"电视转播站\",\"station_code\":\"1072A\",\"lng\":116.8584,\"lat\":38.3254}]";
                List <Region> regions  = JsonConvert.DeserializeObject <List <Region> >(stations);
                List <MonitorPointPollutan> monitorPoints = GetMonitorPointPollutansby9();
                foreach (Region region in regions)
                {
                    String          querys       = "pubtime=" + DateTime.Now.ToShortDateString() + "+" + (DateTime.Now.Hour - 1).ToString() + "%3A00%3A00&station_code=" + region.station_code;
                    String          bodys        = "";
                    String          url          = host + path;
                    HttpWebRequest  httpRequest  = null;
                    HttpWebResponse httpResponse = null;

                    if (0 < querys.Length)
                    {
                        url = url + "?" + querys;
                    }

                    if (host.Contains("https://"))
                    {
                        ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                        httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
                    }
                    else
                    {
                        httpRequest = (HttpWebRequest)WebRequest.Create(url);
                    }
                    httpRequest.Method = method;
                    httpRequest.Headers.Add("Authorization", "APPCODE " + appcode);
                    if (0 < bodys.Length)
                    {
                        byte[] data = Encoding.UTF8.GetBytes(bodys);
                        using (Stream stream = httpRequest.GetRequestStream())
                        {
                            stream.Write(data, 0, data.Length);
                        }
                    }
                    try
                    {
                        httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                    }
                    catch (WebException ex)
                    {
                        httpResponse = (HttpWebResponse)ex.Response;
                    }

                    Stream       st       = httpResponse.GetResponseStream();
                    StreamReader reader   = new StreamReader(st, Encoding.GetEncoding("utf-8"));
                    string       me       = reader.ReadToEnd();
                    message      messagee = JsonConvert.DeserializeObject <message>(me);
                    foreach (MonitorPointPollutan m in monitorPoints.Where(m => m.PointName == messagee.data.station))
                    {
                        HourData hourData = new HourData();
                        hourData.Monitor_PollutionId = m.Id;
                        hourData.MonitorTime         = dateTime;
                        switch (m.PollutantId)
                        {
                        case 11: hourData.AVGValue = messagee.data.AQI == null ? 0 : Convert.ToDecimal(messagee.data.AQI); break;

                        case 12: hourData.AVGValue = messagee.data.PM2_5 == null ? 0 : Convert.ToDecimal(messagee.data.PM2_5); break;

                        case 13: hourData.AVGValue = messagee.data.CO == null ? 0 : Convert.ToDecimal(messagee.data.CO); break;

                        case 14: hourData.AVGValue = messagee.data.NO2 == null ? 0 : Convert.ToDecimal(messagee.data.NO2); break;

                        case 15: hourData.AVGValue = messagee.data.O3 == null ? 0 : Convert.ToDecimal(messagee.data.O3); break;

                        case 16: hourData.AVGValue = messagee.data.SO2 == null ? 0 : Convert.ToDecimal(messagee.data.SO2); break;

                        case 17: hourData.AVGValue = messagee.data.PM10 == null ? 0 : Convert.ToDecimal(messagee.data.PM10); break;
                        }
                        hourDatas.Add(hourData);
                    }
                }
                #endregion
                AddHourData(hourDatas);
            }
        }
Esempio n. 22
0
        public static int GetPicValue(string url, string bodys)
        {
            int             result       = -1;
            HttpWebRequest  httpRequest  = null;
            HttpWebResponse httpResponse = null;
            String          querys       = "";

            if (0 < querys.Length)
            {
                url = url + "?" + querys;
            }

            if (Host.Contains("https://"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
            }
            else
            {
                httpRequest = (HttpWebRequest)WebRequest.Create(url);
            }
            httpRequest.Method = "POST";
            httpRequest.Headers.Add("Authorization", "APPCODE b959e2775668484f8e47cee1edffa0cc");
            //根据API的要求,定义相对应的Content-Type
            httpRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            if (0 < bodys.Length)
            {
                byte[] data = Encoding.UTF8.GetBytes(bodys);
                using (Stream stream = httpRequest.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            try
            {
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();
            }
            catch (WebException ex)
            {
                httpResponse = (HttpWebResponse)ex.Response;
            }

            Stream       st       = httpResponse.GetResponseStream();
            StreamReader reader   = new StreamReader(st, Encoding.GetEncoding("utf-8"));
            string       StrDate  = "";
            string       strValue = "";

            while ((StrDate = reader.ReadLine()) != null)
            {
                strValue += StrDate + "\r\n";
            }

            var _r = (ValidatePicModel)Newtonsoft.Json.JsonConvert.DeserializeObject(strValue, (new ValidatePicModel()).GetType());

            if (_r.showapi_res_body.ret_code == 0)
            {
                result = _r.showapi_res_body.rate;
                if (_r.showapi_res_body.code == "needManualReview")
                {
                    result = 100;
                }
            }
            return(result);
        }
Esempio n. 23
0
 Try <WebRequest> openConnection(Uri uri) => () =>
 WebRequest.CreateDefault(uri);
Esempio n. 24
0
        internal async Task <JsonResponse <TResponse> > GetJsonResponse <TResponse>(Uri baseUri, Uri relativeUri, CancellationToken cancellationToken, IProgress <ProgressReport> progress, AuthToken token = null)
        {
            progress.ReportWhenNotNull(() => ProgressReport.CreateNew(RequestResponseSteps.PreparingUrl_N_Headers, 0, 1));
            //验证对于一般的请求参数修改
            if (token != null)
            {
                var baseUrl = JsonClientHelper.GetBaseUriBuilder(baseUri, relativeUri, this.RequestData.UrlTemplateValues).Uri.ToString();
                token.FillToContext(baseUrl, this);
            }

            var uri = new Uri(JsonClientHelper.GetAbsoultUrl(baseUri, relativeUri, this.RequestData.QueryStringValues, this.RequestData.UrlTemplateValues));

#if DOTNET45
            var webrqst = WebRequest.CreateDefault(uri);
#else
            var webrqst = WebRequest.Create(uri);
#endif

            webrqst.Method = RequestMethod;
            //验证对于底层请求参数修改
            if (token != null)
            {
                token.FillToWebRequest(webrqst, this);
            }

            FillToHeader(webrqst);
            progress.ReportWhenNotNull(() => ProgressReport.CreateNew(RequestResponseSteps.PreparingUrl_N_Headers, 1, 1));

            await FillDataTo(webrqst, cancellationToken, progress).ConfigureAwait(false);

            if (typeof(WebRequest) == (typeof(TResponse)))
            {
                var o = new JsonResponse <WebRequest>(webrqst, webrqst, null, null);
                progress.ReportWhenNotNull(() => ProgressReport.CreateNew(RequestResponseSteps.Deserializing, 1, 1));
                return(o as JsonResponse <TResponse>);
            }

            using (var webrsps = await webrqst.GetResponseAsync().ConfigureAwait(false))
            {
                if (typeof(WebResponse) == (typeof(TResponse)))
                {
                    var o = new JsonResponse <WebResponse>(webrsps, webrqst, webrsps, null);
                    progress.ReportWhenNotNull(() => ProgressReport.CreateNew(RequestResponseSteps.Deserializing, 1, 1));
                    return(o as JsonResponse <TResponse>);
                }
#if SILVERLIGHT_4 || SILVERLIGHT_5 || WINDOWS_PHONE_7
                var h = new Dictionary <string, string[]>();
#endif

#if DOTNET45 || WINDOWS_PHONE_8
                var h = webrsps.Headers.AllKeys
                        .Select(k => new { k, v = webrsps.Headers[k].Split(',') })
                        .ToDictionary(x => x.k, x => x.v);
#endif

#if NETFX_CORE
                var h = webrsps.Headers.AllKeys
                        .Select(k => new { k, v = webrsps.Headers[k].Split(',') })
                        .ToDictionary(x => x.k, x => x.v);
#endif
                var ms           = new MemoryStream();
                var total        = webrsps.ContentLength;
                var current      = 0;
                var buffer       = new byte[4096];
                var sourceStream = webrsps.GetResponseStream();
                var eof          = false;
                while (!eof)
                {
                    progress.ReportWhenNotNull(new Func <ProgressReport> (() => ProgressReport.CreateNew(RequestResponseSteps.GettingResponse, current, total)));
                    cancellationToken.ThrowIfCancellationRequested();
                    var readCount = await sourceStream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);

                    current = current + readCount;

                    eof = (readCount == 0);
                    if (!eof)
                    {
                        ms.Write(buffer, 0, readCount);
                    }
                }

                if (typeof(Stream) == (typeof(TResponse)))
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    var value = ms;
                    var o     = new JsonResponse <Stream>(value, webrqst, webrsps, ms);
                    progress.ReportWhenNotNull(() => ProgressReport.CreateNew(RequestResponseSteps.Deserializing, 1, 1));
                    return(o as JsonResponse <TResponse>);
                }
                else
                {
                    try
                    {
                        progress.ReportWhenNotNull(() => ProgressReport.CreateNew(RequestResponseSteps.Deserializing, 0, 1));
                        ms.Seek(0, SeekOrigin.Begin);
                        var value = (TResponse)JsonSerializerCache <TResponse> .Serializer.ReadObject(ms);

                        ms.Seek(0, SeekOrigin.Begin);
                        var o = new JsonResponse <TResponse>(value, webrqst, webrsps, ms);
                        progress.ReportWhenNotNull(() => ProgressReport.CreateNew(RequestResponseSteps.Deserializing, 1, 1));
                        return(o);
                    }
                    catch (Exception ex)
                    {
                        ms.Seek(0, SeekOrigin.Begin);
                        return(new JsonResponse <TResponse>(
                                   default(TResponse),
                                   webrqst,
                                   webrsps,
                                   ms,
                                   new JsonContractException("Serializing exception", ex, ms, h)
                                   ));
                    }
                }
            }
        }
        private string ExecuteWebRequest(HttpMethod method, Uri uri, string contentParameters, string authHeader)
        {
            WebRequest request;

            if (method == HttpMethod.POST)
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(contentParameters);

                request               = WebRequest.CreateDefault(uri);
                request.Method        = "POST";
                request.ContentType   = "application/x-www-form-urlencoded";
                request.ContentLength = byteArray.Length;

                if (!String.IsNullOrEmpty(OAuthHeaderCode))
                {
                    byte[] API64        = Encoding.UTF8.GetBytes(APIKey + ":" + APISecret);
                    string Api64Encoded = System.Convert.ToBase64String(API64);
                    //Authentication providers needing an "Authorization: Basic/bearer base64(clientID:clientSecret)" header. OAuthHeaderCode might be: Basic/Bearer/empty.
                    request.Headers.Add("Authorization: " + OAuthHeaderCode + " " + Api64Encoded);
                }

                if (!String.IsNullOrEmpty(contentParameters))
                {
                    Stream dataStream = request.GetRequestStream();
                    dataStream.Write(byteArray, 0, byteArray.Length);
                    dataStream.Close();
                }
            }
            else
            {
                request = WebRequest.CreateDefault(GenerateRequestUri(uri.ToString(), contentParameters));
            }

            //Add Headers
            if (!String.IsNullOrEmpty(authHeader))
            {
                request.Headers.Add(HttpRequestHeader.Authorization, authHeader);
            }

            try
            {
                using (WebResponse response = request.GetResponse())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        if (responseStream != null)
                        {
                            using (var responseReader = new StreamReader(responseStream))
                            {
                                return(responseReader.ReadToEnd());
                            }
                        }
                    }
                }
            }
            catch (WebException ex)
            {
                using (Stream responseStream = ex.Response.GetResponseStream())
                {
                    if (responseStream != null)
                    {
                        using (var responseReader = new StreamReader(responseStream))
                        {
                            Logger.ErrorFormat("WebResponse exception: {0}", responseReader.ReadToEnd());
                        }
                    }
                }
            }
            return(null);
        }
Esempio n. 26
0
        public void Configure()
        {
            if (Type == "None")
            {
                log.Info("Removing proxy usage.");
                WebRequest.DefaultWebProxy = null;
            }
            else if (Type == "Custom")
            {
                log.Info("Setting custom proxy.");
                WebProxy wp = new WebProxy();
                wp.Address = new System.Uri(string.Format("http://{0}:{1}", ServerName, Port));
                log.Debug("Using " + wp.Address);
                wp.BypassProxyOnLocal = true;
                if (AuthenticationRequired && !string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password))
                {
                    if (UserName.Contains(@"\"))
                    {
                        try {
                            string[] usernameBits = UserName.Split('\\');
                            wp.Credentials = new NetworkCredential(usernameBits[1], Password, usernameBits[0]);
                        } catch (System.Exception ex) {
                            log.Error("Failed to extract domain from proxy username: "******"Using default proxy (app.config / IE).");
                log.Info("Setting system-wide proxy.");
                IWebProxy iwp = WebRequest.GetSystemWebProxy();
                iwp.Credentials            = CredentialCache.DefaultNetworkCredentials;
                WebRequest.DefaultWebProxy = iwp;
            }

            if (WebRequest.DefaultWebProxy != null)
            {
                try {
                    log.Debug("Testing the system proxy.");
                    String     testUrl  = "http://www.google.com";
                    WebRequest wr       = WebRequest.CreateDefault(new System.Uri(testUrl));
                    System.Uri proxyUri = wr.Proxy.GetProxy(new System.Uri(testUrl));
                    log.Debug("Confirmation of configured proxy: " + proxyUri.OriginalString);
                    if (testUrl != proxyUri.OriginalString)
                    {
                        try {
                            new Extensions.OgcsWebClient().OpenRead(testUrl);
                        } catch (WebException ex) {
                            if (ex.Response != null)
                            {
                                System.IO.Stream       stream = null;
                                System.IO.StreamReader sr     = null;
                                try {
                                    HttpWebResponse hwr = ex.Response as HttpWebResponse;
                                    log.Debug("Proxy error status code: " + hwr.StatusCode + " = " + hwr.StatusDescription);
                                    stream = hwr.GetResponseStream();
                                    sr     = new System.IO.StreamReader(stream);
                                    log.Fail(sr.ReadToEnd());
                                } catch (System.Exception ex2) {
                                    OGCSexception.Analyse("Could not analyse WebException response.", ex2);
                                } finally {
                                    if (sr != null)
                                    {
                                        sr.Close();
                                    }
                                    if (stream != null)
                                    {
                                        stream.Close();
                                    }
                                }
                            }
                            else
                            {
                                OGCSexception.Analyse("Testing proxy connection failed.", ex);
                            }
                        }
                    }
                } catch (System.Exception ex) {
                    OGCSexception.Analyse("Failed to confirm proxy settings.", ex);
                }
            }
        }