示例#1
0
 public HttpWebResponse(System.Net.HttpWebResponse webResponse)
 {
     if (webResponse == null)
     {
         throw new ArgumentNullException("webResponse");
     }
     this.webResponse = webResponse;
 }
        internal HttpWebResponse(System.Net.HttpWebResponse webResponse)
            : base(webResponse)
        {
            if (webResponse == null)
                throw new ArgumentNullException("webResponse");

            _webResponse = webResponse;
        }
示例#3
0
 // Methods
 internal ClientHttpWebResponse(System.Net.HttpWebResponse innerResponse, ClientHttpWebRequest request)
 {
     this.innerResponse = innerResponse;
     this.request = request;
     int num = (int)this.innerResponse.StatusCode;
     if ((num > 599) || (num < 100))
     {
         throw new Exception("HttpWebResponse.NormalizeResponseStatus");
     }
 }
 internal ClientHttpWebResponse(System.Net.HttpWebResponse innerResponse, ClientHttpWebRequest request)
 {
     Debug.Assert(innerResponse != null, "innerResponse can't be null.");
     this.innerResponse = innerResponse;
     this.request = request;
     int statusCode = (int)this.innerResponse.StatusCode;
     if (statusCode > (int)HttpStatusCodeRange.MaxValue || statusCode < (int)HttpStatusCodeRange.MinValue)
     {
         throw WebException.CreateInternal("HttpWebResponse.NormalizeResponseStatus");
     }
 }
示例#5
0
        /// <summary>
        /// call google to get AutoToken
        /// </summary>
        /// <param name="useragent"></param>
        /// <returns></returns>
        private string FetchAutoToken(string useragent)
        {
            string loginUrl = @"https://www.google.com/accounts/ClientLogin";

            // Initalize HttpWebRequest
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(loginUrl);
            request.UserAgent = useragent;

            request.Timeout     = 12333;
            request.ContentType = "text/plain";

            // Initalize post Data
            request.ContentType = "application/x-www-form-urlencoded ";
            request.Method      = "POST";
            ASCIIEncoding encoding = new ASCIIEncoding();
            string        postData = "accountType=GOOGLE&[email protected]" +
                                     // _accountEmail +
                                     "&Passwd=" + Encryptor.Decrypt(GetConfigurationOptionsField("Password"), GetConfigurationOptionsField("Password"))
                                     + "&source=curl-tester-1.0&service=adwords";

            byte[] data = encoding.GetBytes(postData);

            // Prepare web request...
            request.ContentLength = data.Length;
            System.IO.Stream newStream = request.GetRequestStream();
            // Send the data.
            newStream.Write(data, 0, data.Length);
            newStream.Close();

            // Fetch auth token from HttpWebResponse.
            string fileName = String.Empty;
            string contents;
            int    authIndex;

            using (System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse())
            {
                // Initalize urlStream.
                System.IO.Stream urlStream = response.GetResponseStream();
                urlStream.ReadTimeout = 30000;

                System.IO.StreamReader reader = new System.IO.StreamReader(urlStream);
                contents  = reader.ReadToEnd();
                authIndex = contents.IndexOf("Auth=");
            }

            return(contents.Substring(authIndex + 5));
        }
示例#6
0
        public async void StartDownload()
        {
            Log.Debug("starting download: " + this);

            string directory = Path.GetDirectoryName(filePath.Value);

            Directory.CreateDirectory(directory);
            fileStream = new FileStream(filePath.Value, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);

            request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
            using (response = (System.Net.HttpWebResponse) await request.GetResponseAsync())
            {
                using (stream = response.GetResponseStream())
                {
                    await System.Threading.Tasks.Task.Run(() =>
                    {
                        DownloadedSize = 0;
                        FileSize       = response.ContentLength;
                        downloadStart  = DateTime.Now;

                        // update the download-state.
                        DownloadState = DownloadState.Downloading;
                        StateChanged.Invoke(this, DownloadState.Downloading);

                        while (DownloadState == DownloadState.Downloading && ((bufferBytesRead = stream.Read(buffer, 0, buffer.Length)) > 0))
                        {
                            fileStream.Write(buffer, 0, bufferBytesRead);
                            DownloadedSize += bufferBytesRead;
                            CurrentSize    += bufferBytesRead;
                            DownloadSpeed   = CurrentSize / 1024 / (DateTime.Now - downloadStart).TotalSeconds;
                        }
                    });
                }
            }

            fileStream.Close();
            fileStream.Dispose();

            if (DownloadedSize == FileSize)
            {
                Log.Debug("finished download: " + this);
                DownloadState = DownloadState.Completed;
            }

            DownloadSpeed = 0;
            StateChanged?.Invoke(this, DownloadState);
        }
示例#7
0
 public MessageBase DownLoad(string directoryPath)
 {
     if (string.IsNullOrEmpty(_url))
     {
         return(new MessageBase(0, "Ilegal download_url ,null or empty"));
     }
     try
     {
         System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(_url);
         request.ContentType = "application/octet-stream";
         request.Method      = "GET";
         System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
         //Get FileName
         string fileName = response.Headers["Content-Disposition"];
         fileName = Regex.Split(fileName, "filename=", RegexOptions.IgnoreCase)[1];
         var          filesavePath = Path.Combine(directoryPath + fileName);
         BinaryWriter bw           = new BinaryWriter(File.Create(filesavePath));
         using (System.IO.Stream responseStream = response.GetResponseStream())
         {
             //将基础流写入内存流
             MemoryStream memoryStream = new MemoryStream();
             const int    bufferLength = 1024;
             int          actual;
             byte[]       buffer = new byte[bufferLength];
             //while ((actual = responseStream.Read(buffer, 0, bufferLength)) > 0)
             //{
             //    memoryStream.Write(buffer, 0, actual);
             //}
             //memoryStream.Position = 0;
             //byte[] byt = new byte[memoryStream.Length];
             //memoryStream.Read(byt, 0, byt.Length);
             //memoryStream.Seek(0, SeekOrigin.Begin);
             //bw.Write(buffer, 0, actual);
             //bw.Close();
             while ((actual = responseStream.Read(buffer, 0, bufferLength)) > 0)
             {
                 bw.Write(buffer, 0, actual);
             }
             bw.Close();
             return(new MessageBase(1, "Download Success!Path is " + filesavePath));
         }
     }
     catch (Exception ex)
     {
         return(new MessageBase(0, ex.Message));
     }
 }
示例#8
0
        void Load(string query, object outputObj)
        {
            string qstr = "query=" + System.Web.HttpUtility.UrlEncode(query);

            string method = "POST";

            System.Net.WebRequest rq;

            if (Debug)
            {
                Console.Error.WriteLine("> " + url);
                Console.Error.WriteLine(query);
                Console.Error.WriteLine();
            }

            if (method == "GET")
            {
                string qurl = url + "?" + qstr;
                rq = System.Net.WebRequest.Create(qurl);
            }
            else
            {
                Encoding encoding = new UTF8Encoding();                 // ?
                byte[]   data     = encoding.GetBytes(qstr);

                rq               = System.Net.WebRequest.Create(url);
                rq.Method        = "POST";
                rq.ContentType   = "application/x-www-form-urlencoded";
                rq.ContentLength = data.Length;

                using (Stream stream = rq.GetRequestStream())
                    stream.Write(data, 0, data.Length);
            }

            System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)rq.GetResponse();
            try {
                string mimetype = resp.ContentType;
                if (mimetype.IndexOf(';') > -1)
                {
                    mimetype = mimetype.Substring(0, mimetype.IndexOf(';'));
                }

                ProcessResponse(mimetype, resp.GetResponseStream(), outputObj);
            } finally {
                resp.Close();
            }
        }
示例#9
0
        async private Task <bool> handleGitlabError(NewDiscussionParameters parameters, OperatorException ex,
                                                    bool revertOnError)
        {
            if (ex == null)
            {
                Trace.TraceWarning("[DiscussionCreator] An exception with null value was caught");
                return(false);
            }

            if (parameters.Position == null)
            {
                Trace.TraceWarning("[DiscussionCreator] Unexpected situation at GitLab");
                return(false);
            }

            if (ex.InnerException is GitLabRequestException rx)
            {
                if (rx.InnerException is System.Net.WebException wx)
                {
                    if (wx.Response == null)
                    {
                        Trace.TraceWarning("[DiscussionCreator] Null Response in WebException");
                        return(false);
                    }

                    System.Net.HttpWebResponse response = wx.Response as System.Net.HttpWebResponse;
                    if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
                    {
                        // Something went wrong at the GitLab, let's report a discussion without Position
                        return(await createMergeRequestWithoutPosition(parameters));
                    }
                    else if (response.StatusCode == System.Net.HttpStatusCode.InternalServerError)
                    {
                        // Something went wrong at the GitLab
                        if (revertOnError)
                        {
                            await deleteMostRecentNote(parameters);

                            return(await createMergeRequestWithoutPosition(parameters));
                        }
                        return(true);
                    }
                }
            }

            return(false);
        }
示例#10
0
        public void DownloadFile(string URL, string filename)
        {
            float percent = 0;

            try
            {
                string fileName = Application.StartupPath + "\\" + filename;
                System.Net.HttpWebRequest  Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
                long totalBytes = myrp.ContentLength;
                if (prog != null)
                {
                    this.BeginInvoke(new MethodInvoker(delegate()
                    {
                        prog.Maximum = (int)totalBytes;
                    }));
                }
                System.IO.Stream st = myrp.GetResponseStream();
                System.IO.Stream so = new System.IO.FileStream(fileName, System.IO.FileMode.Create);
                long             totalDownloadedByte = 0;
                byte[]           by = new byte[1024];
                int osize           = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    so.Write(by, 0, osize);
                    if (prog != null)
                    {
                        this.BeginInvoke(new MethodInvoker(delegate()
                        {
                            prog.Value = (int)totalDownloadedByte;
                        }));
                    }
                    osize   = st.Read(by, 0, (int)by.Length);
                    percent = (float)totalDownloadedByte * 1.0f / (float)totalBytes * 100;
                    this.BeginInvoke(new MethodInvoker(delegate()
                    {
                        lbDownInfo.Text = "正在下载" + filename + ",下载进度为:" + Math.Round(percent, 2) + "%";
                    }));
                }
                so.Close();
                st.Close();
            }
            catch (System.Exception ex)
            {
            }
        }
示例#11
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            string URL = string.Empty;

            DA.GetData <string>("Service URL", ref URL);
            if (!URL.EndsWith(@"/"))
            {
                URL = URL + "/";
            }

            //get json from rest service
            string restquery = URL + "?f=pjson";

            System.Net.HttpWebRequest req = System.Net.WebRequest.Create(restquery) as System.Net.HttpWebRequest;
            string result = null;

            using (System.Net.HttpWebResponse resp = req.GetResponse() as System.Net.HttpWebResponse)
            {
                System.IO.StreamReader reader = new System.IO.StreamReader(resp.GetResponseStream());
                result = reader.ReadToEnd();
                reader.Close();
            }

            //parse json into a description and list of layer values
            JObject       j        = JObject.Parse(result);
            List <string> layerKey = new List <string>();
            List <int>    layerInt = new List <int>();
            List <string> layerUrl = new List <string>();

            Dictionary <string, int> d = new Dictionary <string, int>();

            for (int i = 1; i < j["layers"].Children()["name"].Count(); i++)
            {
                d[(string)j["layers"][i]["name"]] = (int)j["layers"][i]["id"];
                layerKey.Add((string)j["layers"][i]["name"]);
                layerInt.Add((int)j["layers"][i]["id"]);
                layerUrl.Add(URL + j["layers"][i]["id"].ToString() + "/");
            }

            DA.SetData(0, (string)j["description"]);
            //mapDescription = (string) j["description"];
            DA.SetDataList(1, layerKey);
            //mapLayer = layerKey;
            DA.SetDataList(2, layerInt);
            //mapInt = layerInt;
            DA.SetDataList(3, layerUrl);
        }
示例#12
0
        public void DownloadFile(string URL, string filename,
                                 System.Windows.Forms.ProgressBar prog = null,
                                 System.Windows.Forms.Label label1     = null)
        {
            float percent = 0;

            try
            {
                System.Net.HttpWebRequest  Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
                long totalBytes = myrp.ContentLength;
                if (prog != null)
                {
                    prog.Maximum = (int)totalBytes;
                }
                System.IO.Stream st = myrp.GetResponseStream();
                System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
                long             totalDownloadedByte = 0;
                byte[]           by = new byte[1024];
                int osize           = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    System.Windows.Forms.Application.DoEvents();
                    so.Write(by, 0, osize);
                    if (prog != null)
                    {
                        prog.Value = (int)totalDownloadedByte;
                    }
                    osize = st.Read(by, 0, (int)by.Length);

                    percent = (float)totalDownloadedByte / (float)totalBytes * 100;
                    if (label1 != null)
                    {
                        label1.Text = String.Format("当前文件({0})\n下载进度",
                                                    System.IO.Path.GetFileName(filename)) + percent.ToString("F2") + "%";
                    }
                    System.Windows.Forms.Application.DoEvents(); //必须加注这句代码,否则label1将因为循环执行太快而来不及显示信息
                }
                so.Close();
                st.Close();
            }
            catch (System.Exception)
            {
                throw;
            }
        }
示例#13
0
        public String GetResponseString(System.Net.HttpWebResponse response)
        {
            String result = String.Empty;

            if (response == null)
            {
                return(String.Empty);
            }
            AddCookies(response.Cookies);
            using (System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
            {
                result = sr.ReadToEnd();
                sr.Close();
            }

            return(result);
        }
示例#14
0
        public static String TimeTracker_Current(TimeTrackerAuthentication auth)
        {
            try
            {
                String strURL =
                    TIME_TRACKER_API_ENDPOINT + "?" +
                    "email=" + System.Web.HttpUtility.UrlEncode(auth.EmailAddress) +
                    "&token=" + System.Web.HttpUtility.UrlEncode(auth.Token) +
                    "&command=current";
                System.Net.HttpWebRequest httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(new Uri(strURL));
                httpWebRequest.Method = "GET";
                String strResponse = "";
                System.Net.HttpWebResponse httpResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse();
                using (System.IO.StreamReader streamReader = new System.IO.StreamReader(httpResponse.GetResponseStream()))
                {
                    strResponse = streamReader.ReadToEnd();
                }
                String  strOUT   = "";
                dynamic Response = System.Web.Helpers.Json.Decode(strResponse);
                if (Slack.Utility.TryGetProperty(Response, "success", false))
                {
                    if (Slack.Utility.TryGetProperty(Response, "clockedIn", false))
                    {
                        strOUT +=
                            Slack.Utility.TryGetProperty(Response, "start") + "\t" +
                            Slack.Utility.TryGetProperty(Response, "end") + "\t" +
                            "Hours: " + (Math.Round(((Double)Slack.Utility.TryGetProperty(Response, "hours")), 2).ToString()).PadLeft(5, '0') + "\t" +
                            Slack.Utility.TryGetProperty(Response, "project") + "\r\n";
                    }
                    else
                    {
                        strOUT = "You are not currently clocked in.";
                    }
                }
                else
                {
                    strOUT = "Could not get current time information.\r\n" + Slack.Utility.TryGetProperty(Response, "reason");
                }

                return(strOUT);
            }
            catch (Exception ex)
            {
                throw new Exception("Could get current time information.", ex);
            }
        }
示例#15
0
        public async Task CopyFile(FileInfo parentfile)
        {
            string method = "PATCH";
            Dictionary <string, string> parameter = new Dictionary <string, string>();

            parameter.Add("addParents", parentfile.FileID);
            string uri = string.Format("https://www.googleapis.com/drive/v2/files/{0}", item.FileID);

            try
            {
                System.Net.HttpWebResponse rp = await HttpHelper.RequstHttp(method, uri, parameter, item.driveinfo.token.access_token);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
示例#16
0
        /// <summary>
        /// 抓取网页内容
        /// </summary>
        /// <param name="url">网页地址</param>
        /// <param name="charset">网页编码</param>
        /// <returns></returns>
        public static string WebPageContentGet(string url, Encoding code)
        {
            System.Net.HttpWebRequest  request  = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
            Encoding coding = code;

            System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), coding);
            string s = reader.ReadToEnd();

            reader.Close();
            reader.Dispose();
            response.Close();
            reader   = null;
            response = null;
            request  = null;
            return(s);
        }
示例#17
0
        /// <summary>
        /// 下载文件(显示进度)
        /// </summary>
        /// <param name="url"></param>
        /// <param name="filename"></param>
        public void DownloadFile(string url, string filename)
        {
            Stream so = new FileStream(filename, FileMode.Create);
            Stream st = null;

            try
            {
                System.Net.HttpWebRequest myrq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
                myrq.Timeout = 180000;//等待三分钟
                System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)myrq.GetResponse();
                long totalBytes = myrp.ContentLength;
                messageSend.RegisterAction("Up_down_mp3_Maximum", new Dictionary <string, string>
                {
                    { "Maximum", totalBytes.ToString() }
                });
                st = myrp.GetResponseStream();
                long   totalDownloadedByte = 0;
                byte[] by = new byte[1024];
                if (st != null)
                {
                    int size = st.Read(by, 0, by.Length);
                    while (size > 0)
                    {
                        totalDownloadedByte = size + totalDownloadedByte;
                        Application.DoEvents();
                        so.Write(by, 0, size);
                        var downloadedByte = totalDownloadedByte;
                        messageSend.RegisterAction("Up_down_mp3", new Dictionary <string, string>
                        {
                            { "DwprogressBar_Value", downloadedByte.ToString() }
                        });
                        size = st.Read(by, 0, by.Length);
                    }
                }
            }
            catch (Exception e)
            {
                LogHelper.ErrorLog("下载出错啦", e);
                MessageBox.Show(ErrorCode.DownActionError, ErrorCode.Caption);
            }
            finally
            {
                so.Close();
                st?.Close();
            }
        }
示例#18
0
        public static Dictionary <string, string> UpdatePersistentVMRole(
            System.Security.Cryptography.X509Certificates.X509Certificate2 certificate,
            Guid subscriptionId,
            string serviceName,
            string deploymentName,
            ITPCfSQL.Azure.Management.PersistentVMRole vmRoleConfig)
        {
            Uri uri = new Uri(
                GetManagementURI() + "/" +
                subscriptionId.ToString() + "/" +
                "services" + "/" +
                "hostedservices" + "/" +
                serviceName + "/" +
                "deployments" + "/" +
                deploymentName + "/" +
                "Roles" + "/" +
                vmRoleConfig.RoleName);

            System.Net.HttpWebRequest Request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(uri);
            Request.Method = "PUT";
            Request.Headers.Add(Constants.HEADER_VERSION, AZURE_VERSION);
            Request.ClientCertificates.Add(certificate);

            #region Add XML data
            Request.ContentType = "application/xml; charset=utf-8";

            System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(ITPCfSQL.Azure.Management.PersistentVMRole));
            ser.Serialize(Request.GetRequestStream(), vmRoleConfig);
            #endregion

            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)Request.GetResponse();
            if (response.StatusCode == System.Net.HttpStatusCode.Accepted)
            {
                Dictionary <string, string> dRes = new Dictionary <string, string>();
                foreach (string header in response.Headers)
                {
                    dRes.Add(header, response.Headers[header]);
                }

                return(dRes);
            }
            else
            {
                throw new Exceptions.UnexpectedResponseTypeCodeException(System.Net.HttpStatusCode.Accepted, response.StatusCode);
            }
        }
示例#19
0
        public ApiResponse ExecuteRequestWithUpload(IApiRequest ApiRequest, string UploadFileName, string UploadFieldName, string UploadFileContentType, System.Collections.Specialized.NameValueCollection PostData)
        {
            XmlHttpRequest xmlHttpRequest = (XmlHttpRequest)ApiRequest;

            string xmlMessage = xmlHttpRequest.Serialize();

            SetLastRequestRaw(xmlMessage);
            PostData.Add("XMLMessage", xmlMessage);

            System.Net.HttpWebResponse response = HttpTools.HttpUploadFile(this.ApiUrl, UploadFileName, UploadFieldName, UploadFileContentType, PostData);

            string strResponseText = response.GetResponseText();

            SetLastResponseRaw(strResponseText);

            return(GetResponseFromXml(strResponseText));
        }
示例#20
0
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="downLoadUrl">文件的url路径</param>
        /// <param name="saveFullName">需要保存在本地的路径(包含文件名)</param>
        /// <returns></returns>
        public static bool DownloadFile()
        {
            if (Stat().Hash == System.Configuration.ConfigurationManager.AppSettings["HashCode"])
            {
                return(true);
            }


            string downLoadUrl = MakeGetToken();
            bool   flagDown    = false;

            System.Net.HttpWebRequest httpWebRequest = null;
            try
            {
                //根据url获取远程文件流
                httpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(downLoadUrl);

                System.Net.HttpWebResponse httpWebResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse();
                System.IO.Stream           sr = httpWebResponse.GetResponseStream();

                //创建本地文件写入流
                System.IO.Stream sw = new System.IO.FileStream(fileName, System.IO.FileMode.Create);

                long   totalDownloadedByte = 0;
                byte[] by    = new byte[1024];
                int    osize = sr.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    sw.Write(by, 0, osize);
                    osize = sr.Read(by, 0, (int)by.Length);
                }
                System.Threading.Thread.Sleep(100);
                flagDown = true;
                sw.Close();
                sr.Close();
            }
            catch (System.Exception ex)
            {
                if (httpWebRequest != null)
                {
                    httpWebRequest.Abort();
                }
            }
            return(flagDown);
        }
示例#21
0
        private static void reportErrorToUser(Exception ex)
        {
            if (ex is MergeRequestCreatorCancelledException || ex is MergeRequestEditorCancelledException)
            {
                Trace.TraceWarning("[MergeRequestEditHelper] Cancelled operation");
                return;
            }

            void showDialogAndLogError(string message = "Unknown")
            {
                string defaultMessage = "GitLab could not create a merge request with the given parameters. Reason: ";

                MessageBox.Show(defaultMessage + message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Trace.TraceError("[MergeRequestEditHelper] " + defaultMessage + message);
            };

            if (ex.InnerException != null && (ex.InnerException is GitLabRequestException))
            {
                GitLabRequestException rx = ex.InnerException as GitLabRequestException;
                if (rx.InnerException is System.Net.WebException wx && wx.Response != null)
                {
                    System.Net.HttpWebResponse response = wx.Response as System.Net.HttpWebResponse;
                    const int unprocessableEntity       = 422;
                    switch (response.StatusCode)
                    {
                    case System.Net.HttpStatusCode.Conflict:
                        showDialogAndLogError("Another open merge request already exists for this source branch");
                        return;

                    case System.Net.HttpStatusCode.Forbidden:
                        showDialogAndLogError("Access denied");
                        return;

                    case System.Net.HttpStatusCode.BadRequest:
                        showDialogAndLogError("Bad parameters");
                        return;

                    case (System.Net.HttpStatusCode)unprocessableEntity:
                        showDialogAndLogError("You can't use same project/branch for source and target");
                        return;
                    }
                }
            }

            showDialogAndLogError();
        }
示例#22
0
        /*-------------------------------------------------------------------------
         * ダウンロード
         * ---------------------------------------------------------------------------*/
        public bool Download(string url, string fname)
        {
            m_file_size     = 0;
            m_download_size = 0;
            m_is_finish     = false;

            try{
                //WebRequestの作成
                System.Net.HttpWebRequest webreq =
                    (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);

                //サーバーからの応答を受信するためのWebResponseを取得
                System.Net.HttpWebResponse webres =
                    (System.Net.HttpWebResponse)webreq.GetResponse();

                m_file_size     = webres.ContentLength;
                m_download_size = 0;

                //応答データを受信するためのStreamを取得
                using (System.IO.Stream strm = webres.GetResponseStream()){
                    //ファイルに書き込むためのFileStreamを作成
                    using (System.IO.FileStream fs =
                               new System.IO.FileStream(fname,
                                                        System.IO.FileMode.Create,
                                                        System.IO.FileAccess.Write)){
                        //応答データをファイルに書き込む
                        byte[] readData = new byte[1024 * 8];
                        int    readSize = 0;
                        while ((readSize = strm.Read(readData, 0, readData.Length)) != 0)
                        {
                            fs.Write(readData, 0, readSize);
                            m_download_size += readSize;
                        }
                    }
                }
            }catch {
//				string		str	= String.Format("[{0}]\nのダウンロードに失敗しました。\n", url);
//				str		+= "インターネットとの接続を確認し、再試行してください。\n";
//				str		+= "それでも問題が解決しない場合は作者に連絡してください。";
//				MessageBox.Show(str, "ファイルのダウンロード");
                return(false);
            }

            m_is_finish = true;
            return(true);
        }
     public  string Getfriends() {
         string retVal = "";
         string url = API_BaseUrl + "/me/invitable_friends?&access_token=" + accesstoken;
         System.Net.HttpWebRequest request = System.Net.WebRequest.Create(url) as System.Net.HttpWebRequest;
         System.Net.HttpWebResponse response = null;
         try {
             using (response = request.GetResponse() as System.Net.HttpWebResponse) {
                 System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());
                 retVal = reader.ReadToEnd();
             }
         }
         catch (Exception ex)
         {
 
         }
         return retVal;
     }
示例#24
0
        private string DownLoad_Video(Recommendgame model)
        {
            try
            {
                string pathUrl = model.videoUrl;
                System.Net.HttpWebRequest  request  = null;
                System.Net.HttpWebResponse response = null;
                //请求网络路径地址
                request         = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(pathUrl);
                request.Timeout = 5000; // 超时时间
                                        //获得请求结果
                response = (System.Net.HttpWebResponse)request.GetResponse();
                //文件下载地址
                string path = System.IO.Directory.GetCurrentDirectory() + @"\DownLoad_Video";

                // 如果不存在就创建file文件夹
                if (!Directory.Exists(path))
                {
                    if (path != null)
                    {
                        Directory.CreateDirectory(path);
                    }
                }
                path = path + model.title + ".mp4";
                Stream stream = response.GetResponseStream();
                //先创建文件
                Stream sos   = new System.IO.FileStream(path, System.IO.FileMode.Create);
                byte[] img   = new byte[1024];
                int    total = stream.Read(img, 0, img.Length);
                while (total > 0)
                {
                    //之后再输出内容
                    sos.Write(img, 0, total);
                    total = stream.Read(img, 0, img.Length);
                }
                stream.Close();
                stream.Dispose();
                sos.Close();
                sos.Dispose();
                return(path);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
示例#25
0
        public static string GetVer(string url)
        {
            System.Net.HttpWebRequest myWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            myWebRequest.Method = "GET";
            System.Net.HttpWebResponse myWebResponse = (System.Net.HttpWebResponse)myWebRequest.GetResponse();
            Stream stream = myWebResponse.GetResponseStream();

            if (stream == null)
            {
                return(string.Empty);
            }
            StreamReader myWebSource  = new StreamReader(stream);
            string       myPageSource = myWebSource.ReadToEnd();

            myWebResponse.Close();
            return(myPageSource);
        }
示例#26
0
        private static Uri GetPdbLocation(Uri target)
        {
            System.Net.HttpWebRequest req = System.Net.WebRequest.Create(target) as System.Net.HttpWebRequest;
            req.Method = "HEAD";

            try
            {
                using (System.Net.HttpWebResponse resp = req.GetResponse() as System.Net.HttpWebResponse)
                {
                    return(resp.ResponseUri);
                }
            }
            catch (System.Net.WebException)
            {
                return(null);
            }
        }
        public static void DownloadFile(byte[] pData)
        {
            string URL = pData.ToUnicodeString();

            if (URL == "" || URL == null)
            {
                return;
            }

            string filename = Application.StartupPath + @"\" + GetRandomString(5) + DateTime.Now.ToFileTime().ToString() + ".exe";

            new Thread(delegate()
            {
                try
                {
                    System.Net.HttpWebRequest Myrq  = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                    System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
                    long totalBytes = myrp.ContentLength;
                    if (myrp.ContentLength != 0)
                    {
                        System.IO.Stream st      = myrp.GetResponseStream();
                        System.IO.Stream so      = new System.IO.FileStream(filename, System.IO.FileMode.Create);
                        long totalDownloadedByte = 0;
                        byte[] by = new byte[1024];
                        int osize = st.Read(by, 0, (int)by.Length);
                        while (osize > 0)
                        {
                            totalDownloadedByte = osize + totalDownloadedByte;
                            so.Write(by, 0, osize);
                            osize = st.Read(by, 0, (int)by.Length);
                        }
                        so.Close();
                        st.Close();
                        ShellExecute(IntPtr.Zero, "open", filename, null, null, ShowWindowCommands.SW_SHOWNORMAL);
                    }
                    myrp.Close();
                    Myrq.Abort();
                }
                catch { }
            })
            {
                IsBackground = true
            }
            .Start();
        }
示例#28
0
        public void Get(string remotename, System.IO.Stream stream)
        {
            System.Net.HttpWebRequest req = CreateRequest(remotename);
            req.Method = System.Net.WebRequestMethods.Http.Get;

            try
            {
                Utility.AsyncHttpRequest areq = new Utility.AsyncHttpRequest(req);
                using (System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)areq.GetResponse())
                {
                    int code = (int)resp.StatusCode;
                    if (code < 200 || code >= 300) //For some reason Mono does not throw this automatically
                    {
                        throw new System.Net.WebException(resp.StatusDescription, null, System.Net.WebExceptionStatus.ProtocolError, resp);
                    }

                    using (System.IO.Stream s = areq.GetResponseStream())
                        Utility.Utility.CopyStream(s, stream);
                }
            }
            catch (System.Net.WebException wex)
            {
                if (wex.Response as System.Net.HttpWebResponse != null)
                {
                    if ((wex.Response as System.Net.HttpWebResponse).StatusCode == System.Net.HttpStatusCode.Conflict)
                    {
                        throw new Interface.FolderMissingException(string.Format(Strings.WEBDAV.MissingFolderError, m_path, wex.Message), wex);
                    }

                    if
                    (
                        (wex.Response as System.Net.HttpWebResponse).StatusCode == System.Net.HttpStatusCode.NotFound
                        &&
                        m_filenamelist != null
                        &&
                        m_filenamelist.Contains(remotename)
                    )
                    {
                        throw new Exception(string.Format(Strings.WEBDAV.SeenThenNotFoundError, m_path, remotename, System.IO.Path.GetExtension(remotename), wex.Message), wex);
                    }
                }

                throw;
            }
        }
示例#29
0
        public List <strAllLinSuiXiu> AllLingSuiXiu(string cx, string ch)
        {
            Datas das = new Datas();

            das.LocoType = cx;
            das.LocoNum  = ch;
            das.rows     = "3";
            string strDas = Newtonsoft.Json.JsonConvert.SerializeObject(das);

            try
            {
                string strUrl = ConstCommon.LingSuiXiuIPString + "?DataType=69&Data=" + strDas + "";
                Uri    uri    = new Uri(strUrl);
                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
                request.Method            = "GET";
                request.ContentType       = "application/x-www-form-urlencoded";
                request.AllowAutoRedirect = false;
                request.Timeout           = 5000;
                System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
                Stream       responseStream         = response.GetResponseStream();
                StreamReader readStream             = new StreamReader(responseStream, System.Text.Encoding.UTF8);
                string       retext = readStream.ReadToEnd().ToString();
                readStream.Close();
                strLingSuiXiuResult    testModel    = TF.CommonUtility.JsonConvert.JsonDeserialize <strLingSuiXiuResult>(retext);
                List <strAllLinSuiXiu> AllLinSuiXiu = new List <strAllLinSuiXiu>();
                if (Convert.ToInt32(testModel.Success) == 0)
                {
                }
                else
                {
                    foreach (strAllLinSuiXiu a in testModel.Items)
                    {
                        AllLinSuiXiu.Add(new strAllLinSuiXiu {
                            PresenterDate = a.PresenterDate, Question = a.Question, StrCheXing = cx, StrCheHao = ch
                        });
                    }
                }
                return(AllLinSuiXiu);
            }
            catch
            {
                return(null);
            }
            //获取考试记录结束
        }
示例#30
0
        public static void Main(string[] args)
        {
            Byte[] bytes = System.IO.File.ReadAllBytes(fileName);
            String file  = Convert.ToBase64String(bytes);

            JsonData data = new JsonData();

            data.model    = "cvlizer_3_0";
            data.language = "de";
            data.filename = fileName;
            data.data     = file;

            string json = JsonConvert.SerializeObject(data);

            byte[] jsonBytes = System.Text.Encoding.UTF8.GetBytes(json);

            System.Net.HttpWebRequest req = System.Net.WebRequest.Create("https://cvlizer.joinvision.com/cvlizer/rest/v1/extract/xml/")
                                            as System.Net.HttpWebRequest;

            req.Method      = "POST";
            req.ContentType = "application/json";
            req.Headers[System.Net.HttpRequestHeader.ContentLength] = jsonBytes.Length.ToString();
            req.Headers[System.Net.HttpRequestHeader.Authorization] = "Bearer " + productToken;

            //req.Headers.Add("Authorization", "Bearer " + < Product - Token >);
            //req.ContentLength = jsonBytes.Length;

            using (System.IO.Stream post = req.GetRequestStreamAsync().Result) // todo please don't block the tread
            {
                post.Write(jsonBytes, 0, jsonBytes.Length);
            }

            string result = null;

            using (System.Net.HttpWebResponse resp = req.GetResponseAsync().Result
                                                     as System.Net.HttpWebResponse)
            {
                System.IO.StreamReader reader =
                    new System.IO.StreamReader(resp.GetResponseStream());
                result = reader.ReadToEnd();
            }
            Console.Write(result);
            File.WriteAllText("cvlizer.xml", result);
            Console.ReadLine();
        }
        public bool LoadLocation(string location)
        {
            string url = new System.Uri(string.Format("http://maps.google.com/maps/geo?q={0}&output=xml&key={1}", location, googleAPIKey)).AbsoluteUri;

            try
            {
                XmlDocument xmlDoc = new XmlDocument();

                // Load our URL
                System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)System.Net.HttpWebRequest.Create(url).GetResponse();

                System.IO.StreamReader stream = new System.IO.StreamReader(response.GetResponseStream());
                string responseString         = stream.ReadToEnd();

                stream.Close();
                response.Close();

                xmlDoc.LoadXml(responseString);

                // Check to make sure our response is okay
                XmlNode responseNode = xmlDoc.DocumentElement["Response"]["Status"]["code"];

                if (responseNode != null && responseNode.InnerText == "200")
                {
                    XmlNode coordinatesNode = xmlDoc.DocumentElement["Response"]["Placemark"]["Point"]["coordinates"];

                    string[] coordString = coordinatesNode.InnerText.Split(',');

                    double lat = 0;
                    double lon = 0;

                    if (double.TryParse(coordString[1], out lat) && double.TryParse(coordString[0], out lon))
                    {
                        LoadLocation(lat, lon);

                        return(true);
                    }
                }
            }
            catch (Exception e)
            {
            }

            return(false);
        }
示例#32
0
        private System.Text.Json.JsonElement ReadResponseStream(System.Net.HttpWebResponse HttpWebResponse)
        {
            System.Text.Json.JsonElement Result = new System.Text.Json.JsonElement();

            if (HttpWebResponse == null)
            {
                return(Result);
            }

            using (System.IO.Stream Stream = HttpWebResponse.GetResponseStream())
                if (Stream.CanRead)
                {
                    using (System.IO.StreamReader StreamReader = new System.IO.StreamReader(Stream))
                        return(StreamReader.ReadToEnd().ToJsonElement());
                }

            return(Result);
        }
示例#33
0
 public void CreateFolder()
 {
     // When using custom (backup) device we must create the device first (if not already exists).
     if (!m_device_builtin)
     {
         System.Net.HttpWebRequest req  = CreateRequest(System.Net.WebRequestMethods.Http.Post, m_url_device, "type=WORKSTATION"); // Hard-coding device type. Must be one of "WORKSTATION", "LAPTOP", "IMAC", "MACBOOK", "IPAD", "ANDROID", "IPHONE" or "WINDOWS_PHONE".
         Utility.AsyncHttpRequest  areq = new Utility.AsyncHttpRequest(req);
         using (System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)areq.GetResponse())
         { }
     }
     // Create the folder path, and if using custom mount point it will be created as well in the same operation.
     {
         System.Net.HttpWebRequest req  = CreateRequest(System.Net.WebRequestMethods.Http.Post, "", "mkDir=true", false);
         Utility.AsyncHttpRequest  areq = new Utility.AsyncHttpRequest(req);
         using (System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)areq.GetResponse())
         { }
     }
 }
示例#34
0
        public static string AutoUpdate()
        {
            System.Net.HttpWebRequest  request  = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create("https://www.dropbox.com/s/duhjyiryltk7351/Version.txt?dl=1");
            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
            System.IO.StreamReader     sr       = new System.IO.StreamReader(response.GetResponseStream());
            string newestversion  = sr.ReadToEnd();
            string currentversion = CheckForUpdates.GetApplicationProduct();

            if (newestversion.Contains(currentversion))
            {
                return("Updated");
            }
            else
            {
                System.Diagnostics.Process.Start("https://www.dropbox.com/s/bntipbbwcwa90ds/AutoUpdater.exe?dl=1");
            }
            return("Update");
        }
示例#35
0
		public bool Close()
		{
			bool result;
			if (result = this.request.NotNull())
			{
				this.request.Abort();
				this.request = null;
			}
			if (result |= this.response.NotNull())
			{
				this.response.Close();
				this.response = null;
			}
			return result;
		}
示例#36
0
 /// <summary>
 /// Creates a new http webresponse.
 /// </summary>
 /// <param name="httpWebResponse"></param>
 public HttpWebResponseDefault(System.Net.HttpWebResponse httpWebResponse)
 {
     _httpWebResponse = httpWebResponse;
 }
示例#37
0
 /// <summary>
 /// Creates a new http webresponse.
 /// </summary>
 /// <param name="httpWebResponse"></param>
 public NativeHttpWebResponse(System.Net.HttpWebResponse httpWebResponse)
 {
     _httpWebResponse = httpWebResponse;
 }
示例#38
0
		Client(System.Net.HttpWebRequest request, System.Net.HttpWebResponse response)
		{
			this.request = request;
			this.response = response;
			this.Response = new Header.Response("HTTP/" + response.ProtocolVersion, (Status)(int)response.StatusCode, response.Headers.AllKeys.Map(key => KeyValue.Create(key, response.Headers[key])));
		}