示例#1
0
        /// <summary>
        /// 执行HTTP请求
        /// </summary>
        /// <param name="method"></param>
        /// <param name="url"></param>
        /// <param name="args"></param>
        /// <param name="headers"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string GetResponse(HttpMethod method, string url, string args           = null,
                                         IEnumerable <KeyValuePair <string, string> > headers = null, Encoding encoding = null)
        {
            if (encoding == null)
            {
                encoding = Encoding.UTF8;
            }

            var requestUrl = string.Empty;

            if (!string.IsNullOrEmpty(args) && method == HttpMethod.GET)
            {
                if (url.IndexOf("?") >= 0)
                {
                    requestUrl = url + "&" + args;
                }
                else
                {
                    requestUrl = url + "?" + args;
                }
            }
            else
            {
                requestUrl = url;
            }

            ServicePointManager.Expect100Continue      = false;
            ServicePointManager.DefaultConnectionLimit = 1000;
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);

            request.Credentials = CredentialCache.DefaultCredentials;
            request.Timeout     = 20000;
            request.Method      = method.ToString();
            //设置ContentType
            if (method == HttpMethod.POST)
            {
                request.ContentType = string.Format("application/x-www-form-urlencoded;charset={0}", encoding.WebName);
            }
            else
            {
                request.ContentType = string.Format("text/html;charset={0}", encoding.WebName);
            }
            //设置http headers
            if (headers != null && headers.Count() > 0)
            {
                foreach (KeyValuePair <string, string> header in headers)
                {
                    request.Headers.Add(header.Key, header.Value);
                }
            }

            string          responseData = string.Empty;
            HttpWebResponse response     = null;

            try
            {
                //设置post请求的数据
                if (!string.IsNullOrEmpty(args) && method != HttpMethod.GET)
                {
                    var argBytes = encoding.GetBytes(args);
                    request.ContentLength = argBytes.Length;

                    var stream = request.GetRequestStream();
                    stream.Write(argBytes, 0, argBytes.Length);
                    if (stream != null)
                    {
                        stream.Close();
                    }
                }

                response = (HttpWebResponse)request.GetResponse();
                using (var reader = new StreamReader(response.GetResponseStream(), encoding))
                {
                    responseData = reader.ReadToEnd();
                }
            }
            catch (WebException we)
            {
                response = we.Response as HttpWebResponse;
                using (var reader = new StreamReader(response.GetResponseStream(), encoding))
                {
                    responseData = reader.ReadToEnd();
                }

                throw new HttpException(we.Message, request.RequestUri.ToString(), response.StatusCode, responseData, args);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }
            return(responseData);
        }
示例#2
0
        public static string BuildRequest(Dictionary <string, string[]> sParas, Dictionary <string, string> sPara, string apiMethod)
        {
            Encoding code = Encoding.GetEncoding(_input_charset);

            //待请求参数数组字符串
            string strRequestData = BuildRequestParaToString(sPara, code);

            if (!string.IsNullOrEmpty(strRequestData))
            {
                strRequestData += "&";
            }
            strRequestData += BuildRequestParaToString(sParas, code);

            //把数组转换成流中所需字节数组类型
            byte[] bytesRequestData = code.GetBytes(strRequestData);

            //构造请求地址
            //string strUrl = GATEWAY_NEW + "_input_charset=" + _input_charset;
            string strUrl = GATEWAY_NEW + apiMethod;



            //请求远程HTTP
            string strResult = "";

            try
            {
                //设置HttpWebRequest基本信息
                HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(strUrl);
                myReq.Method      = "post";
                myReq.ContentType = "application/x-www-form-urlencoded";

                //填充POST数据
                myReq.ContentLength = bytesRequestData.Length;
                Stream requestStream = myReq.GetRequestStream();
                requestStream.Write(bytesRequestData, 0, bytesRequestData.Length);
                requestStream.Close();

                //发送POST数据请求服务器
                HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
                Stream          myStream  = HttpWResp.GetResponseStream();

                //获取服务器返回信息
                StreamReader  reader       = new StreamReader(myStream, code);
                StringBuilder responseData = new StringBuilder();
                String        line;
                while ((line = reader.ReadLine()) != null)
                {
                    responseData.Append(line);
                }

                //释放
                myStream.Close();

                strResult = responseData.ToString();
            }
            catch (Exception exp)
            {
                strResult = "报错:" + exp.Message;
            }

            return(strResult);
        }
        public static string BuildRequest(string strUrl, Dictionary <string, string> dicPara, string fileName)
        {
            string contentType = "image/jpeg";
            //待请求参数数组
            FileStream Pic = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            byte[] PicByte = new byte[Pic.Length];
            Pic.Read(PicByte, 0, PicByte.Length);
            int lengthFile = PicByte.Length;

            //构造请求地址

            //设置HttpWebRequest基本信息
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(strUrl);

            //设置请求方式:get、post
            request.Method = "POST";
            //设置boundaryValue
            string boundaryValue = DateTime.Now.Ticks.ToString("x");
            string boundary      = "--" + boundaryValue;

            request.ContentType = "\r\nmultipart/form-data; boundary=" + boundaryValue;
            //设置KeepAlive
            request.KeepAlive = true;
            //设置请求数据,拼接成字符串
            StringBuilder sbHtml = new StringBuilder();

            foreach (KeyValuePair <string, string> key in dicPara)
            {
                sbHtml.Append(boundary + "\r\nContent-Disposition: form-data; name=\"" + key.Key + "\"\r\n\r\n" + key.Value + "\r\n");
            }
            sbHtml.Append(boundary + "\r\nContent-Disposition: form-data; name=\"pic\"; filename=\"");
            sbHtml.Append(fileName);
            sbHtml.Append("\"\r\nContent-Type: " + contentType + "\r\n\r\n");
            string postHeader = sbHtml.ToString();
            //将请求数据字符串类型根据编码格式转换成字节流
            Encoding code = Encoding.GetEncoding("UTF-8");

            byte[] postHeaderBytes = code.GetBytes(postHeader);
            byte[] boundayBytes    = Encoding.ASCII.GetBytes("\r\n" + boundary + "--\r\n");
            //设置长度
            long length = postHeaderBytes.Length + lengthFile + boundayBytes.Length;

            request.ContentLength = length;

            //请求远程HTTP
            Stream requestStream = request.GetRequestStream();
            Stream myStream      = null;

            try
            {
                //发送数据请求服务器
                requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                requestStream.Write(PicByte, 0, lengthFile);
                requestStream.Write(boundayBytes, 0, boundayBytes.Length);
                HttpWebResponse HttpWResp = (HttpWebResponse)request.GetResponse();
                myStream = HttpWResp.GetResponseStream();
            }
            catch (WebException e)
            {
                //LogResult(e.Message);
                return("");
            }
            finally
            {
                if (requestStream != null)
                {
                    requestStream.Close();
                }
            }

            //读取处理结果
            StreamReader  reader       = new StreamReader(myStream, code);
            StringBuilder responseData = new StringBuilder();

            String line;

            while ((line = reader.ReadLine()) != null)
            {
                responseData.Append(line);
            }
            myStream.Close();
            Pic.Close();

            return(responseData.ToString());
        }
        public async void Download(Download video)
        {
            using (var cli = Client.For(new YouTube())) //use a libvideo client to get video metadata
            {
                IEnumerable <YouTubeVideo> downloadLinks = null;

                try
                {
                    downloadLinks = cli.GetAllVideos(video.VideoData.Url).OrderBy(br => - br.AudioBitrate); //sort by highest audio quality
                }
                catch (ArgumentException)
                {
                    video.DownloadFailed = true;
                    downloadManager.RemoveActive(video);
                    //invalid url
                    gui.DisplayMessage("Invalid URL!");

                    threadHandler.RemoveActive(Thread.CurrentThread);
                    Thread.CurrentThread.Abort();
                }

                YouTubeVideo highestQuality = null;

                try
                {
                    highestQuality = downloadLinks.First(); //grab best quality link
                }
                catch
                {
                    video.DownloadFailed = true;
                    downloadManager.RemoveActive(video);
                    gui.DisplayMessage("Unable to download video");
                    gui.OnProgressChanged();
                    return;
                }

                //setup http web request to get video bytes
                var asyncRequest = await highestQuality.GetUriAsync();

                var request = (HttpWebRequest)HttpWebRequest.Create(Convert.ToString(asyncRequest));
                request.AllowAutoRedirect = true;
                request.Method            = "GET";
                request.Proxy             = HttpWebRequest.DefaultWebProxy;
                request.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;

                //execute request and save bytes to buffer
                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    var len    = response.ContentLength;
                    var buffer = new byte[256];
                    using (var stream = response.GetResponseStream())
                    {
                        stream.ReadTimeout = 5000;
                        using (var tempbytes = new TempFile())
                        {
                            FileStream bytes = new FileStream(tempbytes.Path, FileMode.Open);
                            while (bytes.Length < len)
                            {
                                try
                                {
                                    var read = stream.Read(buffer, 0, buffer.Length);
                                    if (read > 0)
                                    {
                                        bytes.Write(buffer, 0, read);

                                        double percentage = bytes.Length * 100 / len;
                                        if (video.DownloadProgress != percentage)
                                        {
                                            video.SetDownloadProgress(percentage);
                                            gui.OnProgressChanged();
                                        }
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                catch
                                {
                                    video.DownloadFailed = true;
                                    downloadManager.RemoveActive(video);
                                    //thread aborted
                                    return;
                                }
                            }

                            //check integrity of byte array
                            if (bytes.Length != len)
                            {
                                video.DownloadFailed = true;
                                downloadManager.RemoveActive(video);
                                gui.DisplayMessage("File content is corrupted!");
                                threadHandler.RemoveActive(Thread.CurrentThread);
                                Thread.CurrentThread.Abort();
                            }
                            else
                            {
                                if (video.Bitrate == 0) //video
                                {
                                    video.SetConvertProgress(100);
                                    string videoPath = Path.Combine(downloadManager.DownloadsPath, highestQuality.FullName);
                                    File.Copy(tempbytes.Path, videoPath, true);

                                    gui.DisplayMessage("Successful!");
                                }
                                else //mp3
                                {
                                    //create temp video file to convert to mp3 and dispose of when done
                                    TimeSpan duration = GetVideoDuration(tempbytes.Path);

                                    string mp3Name   = highestQuality.FullName + ".mp3";
                                    string audioPath = Path.Combine(downloadManager.DownloadsPath, mp3Name);

                                    ToMp3(tempbytes.Path, audioPath, duration, video, video.Bitrate); //convert to mp3
                                }
                            }

                            bytes.Dispose();
                            bytes.Close();
                        }
                    }
                }
            }

            downloadManager.RemoveActive(video);
        }
    public bool postComment(int articleID, string name, string location, string text)
    {
        HttpWebRequest postRequest = (HttpWebRequest)HttpWebRequest.Create(NewsUrl + articleID + "/comments/post/");

        postRequest.Method      = "POST";
        postRequest.ContentType = "text/xml";

        XmlDocument doc            = new XmlDocument();
        XmlElement  commentElement = doc.CreateElement("comment");

        XmlElement idElement = doc.CreateElement("id");

        idElement.InnerText = "0";
        XmlElement publishedDateElement = doc.CreateElement("publishedDate");

        publishedDateElement.InnerText = System.DateTime.Now.ToString("s");
        XmlElement nameElement = doc.CreateElement("name");

        nameElement.InnerText = name;
        XmlElement locationElement = doc.CreateElement("location");

        locationElement.InnerText = location;
        XmlElement textElement = doc.CreateElement("text");

        textElement.InnerText = text;

        commentElement.AppendChild(idElement);
        commentElement.AppendChild(publishedDateElement);
        commentElement.AppendChild(nameElement);
        commentElement.AppendChild(locationElement);
        commentElement.AppendChild(textElement);

        doc.AppendChild(commentElement);

        string postData = doc.OuterXml;

        postRequest.ContentLength = postData.Length;

        try
        {
            Stream requestStream = postRequest.GetRequestStream();
            requestStream.Write(Encoding.UTF8.GetBytes(postData.ToCharArray()), 0, postData.Length);
            requestStream.Close();

            WebResponse response       = postRequest.GetResponse();
            var         responseStatus = ((HttpWebResponse)response).StatusDescription;
            if (responseStatus == "OK")
            {
                Stream       responseStream = response.GetResponseStream();
                StreamReader reader         = new StreamReader(responseStream, Encoding.UTF8);
                XmlDocument  responseAsXML  = new XmlDocument();
                responseAsXML.LoadXml(reader.ReadToEnd());

                if (responseAsXML.InnerText == "true")
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
        catch (Exception ex)
        {
            return(false);
        }
    }
        private void DoDownload(Bundle BundleInfo, NetworkReachability reachability)
        {
            Debug.Log("Download Thread Started: " + BundleInfo.assetBundleName);

            NetworkReachability startingReachability = reachability;
            string     downloadLocation = AssetBundleManager.Instance.CurrentVersionDownloadLocation + "/" + BundleInfo.assetBundleName;
            FileInfo   tempFileInfo     = new FileInfo(downloadLocation + ".incomplete");
            FileStream saveFileStream   = null;

            try
            {
                Debug.Log("AssetBundler DoDownload " + BundleInfo.assetBundleName + " to " + AssetBundleManager.Instance.CurrentVersionDownloadLocation);
                CreateDownloadDirectory();
                long existingLength = 0;
                if (tempFileInfo.Exists)
                {
                    existingLength = tempFileInfo.Length;
                }
                else
                {
                    //making file incomplete, to mark it for future automatic download
                    try
                    {
                        FileStream fs = tempFileInfo.Create();
                        fs.Close();
                    }
                    catch (Exception e)
                    {
                        //if we can't make a temp file, we quit. go away
                        Debug.LogException(e);
                        Debug.LogError("AssetBundler DoDownload: Critical failure in creating temp file: " + e.ToString());
                        AssetBundleStateChanged.Invoke(this, new AssetBundleStateChangedEventArgs(BundleInfo.assetBundleName, AssetBundleDownloadState.Blocked, "FAILED_TO_WRITE_TO_DISK"));
                        return;
                    }
                }
                Debug.Log("AssetBundler DoDownload: Resuming incomplete DL. " + existingLength + " bytes downloaded already.");

                string downloadURL = AssetBundleManager.Instance.BundleServerURL + BundleInfo.assetBundleName;
                Debug.Log("AssetBundler DoDownload: " + downloadURL);
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(downloadURL);
                request.Timeout          = 5000; //5 secs timeout
                request.ReadWriteTimeout = 5000;
                request.AddRange((int)existingLength, (int)BundleInfo.downloadSizeBytes);
                request.KeepAlive = false;

                Debug.Log("Request URI: " + request.RequestUri.AbsoluteUri);
                bool didComplete = false;
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    if (response.ContentLength == 0)
                    {
                        //no more to download from the server
                        if (existingLength >= BundleInfo.downloadSizeBytes)
                        {
                            didComplete = true;
                        }
                        else
                        {
                            throw new Exception("Error. Data on server not sufficient: " + existingLength + " bytes available, expected " + BundleInfo.downloadSizeBytes);
                        }
                    }

                    long serverFileSize = existingLength + response.ContentLength; //response.ContentLength gives me the size that is remaining to be downloaded

                    bool downloadResumable;                                        // need it for not sending any progress
                    int  responseCode = (int)response.StatusCode;
                    downloadResumable = CheckForResumeableReponseCode(BundleInfo, downloadURL, responseCode);
                    if (!downloadResumable)
                    {
                        existingLength = 0;
                    }

                    DownloadProgressChanged.Invoke(this, new DownloadProgressChangedEventArgs(BundleInfo.assetBundleName, existingLength, 0));

                    using (saveFileStream = tempFileInfo.Open(downloadResumable ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
                    {
                        using (Stream stream = response.GetResponseStream())
                        {
                            stream.ReadTimeout = 5000;

                            byte[]    downBuffer      = new byte[4096];
                            long      totalReceived   = existingLength;
                            long      sessionReceived = 0;
                            Stopwatch stopwatch       = Stopwatch.StartNew();
                            while (totalReceived < serverFileSize)
                            {
#if !PRODUCTION && !PREPRODUCTION
                                bool paused = false;// Assets.Code.Common.DebugOptions.GetToggleValue(Assets.Code.Common.DebugToggle.downloadsPaused);
                                if (paused)
                                {
                                    Thread.Sleep(100);
                                    continue;
                                }
                                DebugNoInterentConnection();

                                DebugThrottleConnectionSpeed();
#endif

                                //if connection has downgraded to a non-allowed network,
                                //or if user has changed the current prioritised download, this pauses the download
                                if (startingReachability != AssetBundleManager.Instance.CurrentReachability ||
                                    AssetBundleManager.Instance.CheckAndResetCurrentPriorityChanged() ||
                                    AssetBundleManager.Instance.CheckAndResetDownloadTimeout())
                                {
                                    AssetBundleStateChanged.Invoke(this, new AssetBundleStateChangedEventArgs(BundleInfo.assetBundleName, AssetBundleDownloadState.Queued));
                                    AssetBundleManager.Instance.ResetPollingTime();  //we reset the poll to start the next download immediately
                                    stopwatch.Stop();
                                    stream.Close();
                                    response.Close();
                                    saveFileStream.Close();
                                    saveFileStream = null;
                                    return;
                                }

                                int byteSize = stream.Read(downBuffer, 0, downBuffer.Length);
                                saveFileStream.Write(downBuffer, 0, byteSize);
                                totalReceived   += byteSize;
                                sessionReceived += byteSize;



                                float currentSpeed = sessionReceived / (float)stopwatch.Elapsed.TotalSeconds;
                                DownloadProgressChanged.Invoke(this, new DownloadProgressChangedEventArgs(BundleInfo.assetBundleName, totalReceived, (long)currentSpeed));
                            }
                            didComplete = true;
                            stopwatch.Stop();
                            stream.Close();
                        }
                    }
                    response.Close();
                    saveFileStream.Close();
                    saveFileStream = null;
                }
                if (didComplete)
                {
                    Debug.Log("AssetBundler DoDownload. Completed. Throwing to CRC Check.");
                    //download completed
                    AssetBundleStateChanged.Invoke(this, new AssetBundleStateChangedEventArgs(BundleInfo.assetBundleName, AssetBundleDownloadState.CRCCheck));
                    AssetBundleManager.Instance.ResetPollingTime(); //we reset the poll to start the next download immediately
                }
            }
            catch (WebException we)
            {
                //416 error means we requested some bytes which don't exist.
                //this means the local game is expecting more data than the server has.
                //in this case, the file must be finished (no more data on the server), so we throw it to a CRC check to confirm
                if ((int)we.Status == 416)
                {
                    Debug.LogWarning("AssetBundler DoDownload: Error 416. Assuming File is completed");
                    //this is considered an error for retry purposes
                    AssetBundleStateChanged.Invoke(this, new AssetBundleStateChangedEventArgs(BundleInfo.assetBundleName, AssetBundleDownloadState.CRCCheck, "ERROR_416_FROM_SERVER"));
                }
                if (we.Status == WebExceptionStatus.Timeout)
                {
                    Debug.LogException(we);
                    Debug.LogWarning("Connection Timed Out, likly due to poor or loss of connection, restarting bundle download");
                    AssetBundleStateChanged.Invoke(this, new AssetBundleStateChangedEventArgs(BundleInfo.assetBundleName, AssetBundleDownloadState.CRCCheck));
                }
                else
                {
                    Debug.LogException(we);
                    Debug.LogError("AssetBundler DoDownload: Exception caused assetbundle download failure " + BundleInfo.assetBundleName + " . Performing full file/CRC to work out file status: " + we.ToString());
                    AssetBundleStateChanged.Invoke(this, new AssetBundleStateChangedEventArgs(BundleInfo.assetBundleName, AssetBundleDownloadState.CRCCheck)); //no error because timeouts aren't a problem with the bundle
                }
            }
            catch (IOException ioe)
            {
                Debug.LogException(ioe);
                Debug.LogError("AssetBundler DoDownload: IO/Write Exception. Deleting offending file: " + tempFileInfo.Name + ": " + ioe.ToString());
                AssetBundleDownloadCorruptedOrBroken.Invoke(this, new AssetBundleDeleteAssetBundleFileEventArgs(BundleInfo.assetBundleName, "ASSETBUNDLE_IO_WRITE_EXCEPTION"));
                //kick it right back off again
            }
            catch (ObjectDisposedException objectDisposedException)
            {
                Debug.LogWarning(objectDisposedException.Message);
                Debug.LogWarning("Aborting download " + BundleInfo.assetBundleName + ", likly due to loss of connection, recheck bundle");
                AssetBundleStateChanged.Invoke(this, new AssetBundleStateChangedEventArgs(BundleInfo.assetBundleName, AssetBundleDownloadState.CRCCheck));
            }
            catch (ThreadAbortException)
            {
                Debug.LogWarning("AssetBundler DoDownload: Thread aborted. Assuming intentionally.");
                //AssetBundleStateChanged.Invoke(this, new AssetBundleStateChangedEventArgs(assetBundleQueueInfo.AssetBundleName, AssetBundleDownloadState.CRCCheck, ""));
            }
            catch (Exception e)
            {
                Debug.LogException(e);
                Debug.LogError("AssetBundler DoDownload: Exception caused assetbundle download failure. Performing full file/CRC to work out file status. Error:  " + e.ToString());
                AssetBundleStateChanged.Invoke(this, new AssetBundleStateChangedEventArgs(BundleInfo.assetBundleName, AssetBundleDownloadState.CRCCheck, e.ToString()));
            }
            finally
            {
                if (saveFileStream != null)
                {
                    saveFileStream.Close();
                    saveFileStream = null;
                }
            }
            Debug.Log("Download Thread Ended: " + BundleInfo.assetBundleName);
        }
        /// <summary>
        /// 获取HTML
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="postData">post 提交的字符串</param>
        /// <param name="isPost">是否是post</param>
        /// <param name="cookieContainer">CookieContainer</param>
        /// <returns>html </returns>
        public static string GetHtml(string url, string postData, bool isPost, ref CookieContainer cookieContainer)
        {
            if (string.IsNullOrEmpty(postData))
            {
                return(GetHtml(url, ref cookieContainer));
            }

            Thread.Sleep(NetworkDelay);

            currentTry++;

            HttpWebRequest  httpWebRequest  = null;
            HttpWebResponse httpWebResponse = null;

            try {
                byte[] byteRequest = Encoding.Default.GetBytes(postData);

                httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                httpWebRequest.CookieContainer = cookieContainer;
                httpWebRequest.ContentType     = contentType;
                httpWebRequest.ServicePoint.ConnectionLimit = maxTry;
                httpWebRequest.Referer       = url;
                httpWebRequest.Accept        = accept;
                httpWebRequest.UserAgent     = userAgent;
                httpWebRequest.Method        = isPost ? "POST" : "GET";
                httpWebRequest.ContentLength = byteRequest.Length;

                Stream stream = httpWebRequest.GetRequestStream();
                stream.Write(byteRequest, 0, byteRequest.Length);
                stream.Close();

                httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                Stream       responseStream = httpWebResponse.GetResponseStream();
                StreamReader streamReader   = new StreamReader(responseStream, encoding);
                string       html           = streamReader.ReadToEnd();
                streamReader.Close();
                responseStream.Close();
                currentTry = 0;

                httpWebRequest.Abort();
                httpWebResponse.Close();

                return(html);
            }
            catch (Exception e) {
                if (currentTry <= maxTry)
                {
                    GetHtml(url, postData, isPost, ref cookieContainer);
                }
                currentTry--;

                if (httpWebRequest != null)
                {
                    httpWebRequest.Abort();
                }
                if (httpWebResponse != null)
                {
                    httpWebResponse.Close();
                }
                return(string.Empty);
            }
        }
    protected void createEnvelope()
    {
        // Set up the envelope
        CreateEnvelopeRequest createEnvelopeRequest = new CreateEnvelopeRequest();

        createEnvelopeRequest.emailSubject = "Kitchen Sink Example";
        createEnvelopeRequest.status       = "sent";
        createEnvelopeRequest.emailBlurb   = "Example of how different smart anchors work";

        // Define first signer
        Signer signer = new Signer();

        signer.email        = email.Value;
        signer.name         = firstname.Value + " " + lastname.Value;
        signer.recipientId  = 1;
        signer.routingOrder = "1";
        signer.roleName     = "Signer1";
        signer.clientUserId = RandomizeClientUserID();  // First signer is embedded

        // Add tabs for the signer
        signer.tabs = new Tabs();
        signer.tabs.signHereTabs = new List <SignHereTab>();
        SignHereTab signHereTab = new SignHereTab();

        signHereTab.documentId               = "1";
        signHereTab.tabId                    = "1";
        signHereTab.anchorString             = "~?";
        signHereTab.anchorIgnoreIfNotPresent = "true";
        signHereTab.name = "PrimarySignerSignature";
        signer.tabs.signHereTabs.Add(signHereTab);


        signer.tabs.dateSignedTabs = new List <DateSignedTab>();
        DateSignedTab dateSignedTab = new DateSignedTab();

        dateSignedTab.documentId               = "1";
        dateSignedTab.tabId                    = "2";
        dateSignedTab.anchorString             = "~!";
        dateSignedTab.anchorIgnoreIfNotPresent = "true";
        dateSignedTab.name = "PrimarySignerDateSigned";
        signer.tabs.dateSignedTabs.Add(dateSignedTab);

        // Define a document
        Document document = new Document();

        document.documentId            = "1";
        document.name                  = "Sample Form";
        document.transformPdfFields    = "true";
        document.fileExtension         = "doc";
        document.htmlDefinition        = new HtmlDefinition();
        document.htmlDefinition.source = "document";
        document.htmlDefinition.displayAnchorPrefix = "";
        document.htmlDefinition.maxScreenWidth      = 0;
        document.htmlDefinition.removeEmptyTags     = "table,tr,p";
        document.htmlDefinition.headerLabel         = "<h1 style='color:#E20074;text-align:center;font-family:Tele-Grotesk, Arial, Helvetica;'>Examples of Smart Sections</h1><h2 style = 'text-align:center;font-family:Tele-Grotesk, Arial, Helvetica;'> Simply scroll down to review.</ h2><div style = 'margin-top:20px;margin-bottom:20px;border-bottom:solid 2px #dedede;'></ div >";

        // Define the display anchors
        document.htmlDefinition.displayAnchors = new List <DisplayAnchor>();
        DisplayAnchor displayAnchor = new DisplayAnchor();

        displayAnchor.startAnchor                           = "$Docu$printonlyS$";
        displayAnchor.endAnchor                             = "$Docu$printonlyE$";
        displayAnchor.removeEndAnchor                       = true;
        displayAnchor.removeStartAnchor                     = true;
        displayAnchor.caseSensitive                         = true;
        displayAnchor.displaySettings                       = new DisplaySettings();
        displayAnchor.displaySettings.display               = "print_only";
        displayAnchor.displaySettings.tableStyle            = "";
        displayAnchor.displaySettings.cellStyle             = "";
        displayAnchor.displaySettings.labelWhenOpened       = "";
        displayAnchor.displaySettings.scrollToTopWhenOpened = true;
        displayAnchor.displaySettings.hideLabelWhenOpened   = true;
        displayAnchor.displaySettings.displayLabel          = "";
        document.htmlDefinition.displayAnchors.Add(displayAnchor);

        DisplayAnchor displayAnchor2 = new DisplayAnchor();

        displayAnchor2.startAnchor                           = "$tmo$tila$";
        displayAnchor2.endAnchor                             = "$tmo$tila$";
        displayAnchor2.removeEndAnchor                       = true;
        displayAnchor2.removeStartAnchor                     = true;
        displayAnchor2.caseSensitive                         = true;
        displayAnchor2.displaySettings                       = new DisplaySettings();
        displayAnchor2.displaySettings.display               = "responsive_table_single_column";
        displayAnchor2.displaySettings.tableStyle            = "margin-bottom:20px;";
        displayAnchor2.displaySettings.cellStyle             = "text-align:center;border:solid 3px #333;margin:5px;padding:5px;background-color:#eaeaea;~text-align:center;border:solid 3px #333;margin:5px;padding:5px;background-color:#eaeaea;~text-align:center;border:solid 1px #999;margin:5px;padding:5px;background-color:#eaeaea;";
        displayAnchor2.displaySettings.labelWhenOpened       = "";
        displayAnchor2.displaySettings.scrollToTopWhenOpened = true;
        displayAnchor2.displaySettings.hideLabelWhenOpened   = true;
        displayAnchor2.displaySettings.displayLabel          = "";
        document.htmlDefinition.displayAnchors.Add(displayAnchor2);

        DisplayAnchor displayAnchor5 = new DisplayAnchor();

        displayAnchor5.startAnchor                           = "$Docu$collapsedS$";
        displayAnchor5.endAnchor                             = "$Docu$collapsedE$";
        displayAnchor5.removeEndAnchor                       = true;
        displayAnchor5.removeStartAnchor                     = true;
        displayAnchor5.caseSensitive                         = true;
        displayAnchor5.displaySettings                       = new DisplaySettings();
        displayAnchor5.displaySettings.display               = "collapsed";
        displayAnchor5.displaySettings.tableStyle            = "";
        displayAnchor5.displaySettings.cellStyle             = "";
        displayAnchor5.displaySettings.labelWhenOpened       = "";
        displayAnchor5.displaySettings.scrollToTopWhenOpened = true;
        displayAnchor5.displaySettings.hideLabelWhenOpened   = false;
        displayAnchor5.displaySettings.displayLabel          = @"<div style='display:flex;flex-flow:row wrap;align-items:center;min-height:40px;border-top:solid 1px #dedede;font-size:24px;color:#9d2624'><div style = 'flex:none;width:90%;padding:5px;'>Declaration Of Independence</div><div style='width:10%;text-align:right;padding:5px;'><a><i class='icon icon-caret-large-down' style='color:#000;'></i></a></div></div>";
        document.htmlDefinition.displayAnchors.Add(displayAnchor5);

        DisplayAnchor displayAnchor3 = new DisplayAnchor();

        displayAnchor3.startAnchor                           = "$Docu$collapsibleS$";
        displayAnchor3.endAnchor                             = "$Docu$collapsibleE$";
        displayAnchor3.removeEndAnchor                       = true;
        displayAnchor3.removeStartAnchor                     = true;
        displayAnchor3.caseSensitive                         = true;
        displayAnchor3.displaySettings                       = new DisplaySettings();
        displayAnchor3.displaySettings.display               = "collapsible";
        displayAnchor3.displaySettings.tableStyle            = "";
        displayAnchor3.displaySettings.cellStyle             = "";
        displayAnchor3.displaySettings.labelWhenOpened       = "";
        displayAnchor3.displaySettings.scrollToTopWhenOpened = true;
        displayAnchor3.displaySettings.hideLabelWhenOpened   = false;
        displayAnchor3.displaySettings.displayLabel          = @"<div style='display:flex;flex-flow:row wrap;align-items:center;min-height:40px;border-top:solid 1px #dedede;font-size:24px;color:#9d2624'><div style = 'flex:none;width:90%;padding:5px;'>Declaration Of Independence</div><div style='width:10%;text-align:right;padding:5px;'><a><i class='icon icon-caret-large-down' style='color:#000;'></i></a></div></div>";
        document.htmlDefinition.displayAnchors.Add(displayAnchor3);

        DisplayAnchor displayAnchor4 = new DisplayAnchor();

        displayAnchor4.startAnchor                           = "$Docu$inlineS$";
        displayAnchor4.endAnchor                             = "$Docu$inlineE$";
        displayAnchor4.removeEndAnchor                       = true;
        displayAnchor4.removeStartAnchor                     = true;
        displayAnchor4.caseSensitive                         = true;
        displayAnchor4.displaySettings                       = new DisplaySettings();
        displayAnchor4.displaySettings.display               = "inline";
        displayAnchor4.displaySettings.labelWhenOpened       = "";
        displayAnchor4.displaySettings.scrollToTopWhenOpened = true;
        displayAnchor4.displaySettings.hideLabelWhenOpened   = true;
        displayAnchor4.displaySettings.displayLabel          = "Highlight the following section";
        displayAnchor4.displaySettings.inlineOuterStyle      = "background-color:#ff0; padding:10px;";
        document.htmlDefinition.displayAnchors.Add(displayAnchor4);

        // Define an inline template
        InlineTemplate inline1 = new InlineTemplate();

        inline1.sequence           = "2";
        inline1.recipients         = new Recipients();
        inline1.recipients.signers = new List <Signer>();
        inline1.recipients.signers.Add(signer);


        // Add the inline template to a CompositeTemplate
        CompositeTemplate compositeTemplate1 = new CompositeTemplate();

        compositeTemplate1.inlineTemplates = new List <InlineTemplate>();
        compositeTemplate1.inlineTemplates.Add(inline1);
        compositeTemplate1.document = document;

        // Add compositeTemplate to the envelope
        createEnvelopeRequest.compositeTemplates = new List <CompositeTemplate>();
        createEnvelopeRequest.compositeTemplates.Add(compositeTemplate1);
        createEnvelopeRequest.brandId = ConfigurationManager.AppSettings["MomentumBrandID"];


        string output = JsonConvert.SerializeObject(createEnvelopeRequest);

        // Specify a unique boundary string that doesn't appear in the json or document bytes.
        string Boundary = "MY_BOUNDARY";

        // Set the URI
        HttpWebRequest request = HttpWebRequest.Create(ConfigurationManager.AppSettings["DocuSignServer"] + "/restapi/vdev/accounts/" + ConfigurationManager.AppSettings["API.AccountId"] + "/envelopes") as HttpWebRequest;

        // Set the method
        request.Method = "POST";

        // Set the authentication header
        request.Headers["X-DocuSign-Authentication"] = GetSecurityHeader();

        // Set the overall request content type aand boundary string
        request.ContentType = "multipart/form-data; boundary=" + Boundary;
        request.Accept      = "application/json";

        // Start forming the body of the request
        Stream reqStream = request.GetRequestStream();

        // write boundary marker between parts
        WriteStream(reqStream, "\n--" + Boundary + "\n");

        // write out the json envelope definition part
        WriteStream(reqStream, "Content-Type: application/json\n");
        WriteStream(reqStream, "Content-Disposition: form-data\n");
        WriteStream(reqStream, "\n"); // requires an empty line between the header and the json body
        WriteStream(reqStream, output);

        // write out the form bytes for the first form
        WriteStream(reqStream, "\n--" + Boundary + "\n");
        WriteStream(reqStream, "Content-Type: application/pdf\n");
        WriteStream(reqStream, "Content-Disposition: file; filename=\"Sample_Form\"; documentId=1\n");
        WriteStream(reqStream, "\n");
        if (File.Exists(Server.MapPath("~/App_Data/kitchensink.pdf")))
        {
            // Read the file contents and write them to the request stream
            byte[] buf = new byte[4096];
            int    len;
            // read contents of document into the request stream
            FileStream fileStream = File.OpenRead(Server.MapPath("~/App_Data/kitchensink.pdf"));
            while ((len = fileStream.Read(buf, 0, 4096)) > 0)
            {
                reqStream.Write(buf, 0, len);
            }
            fileStream.Close();
        }


        // wrte the end boundary marker - ensure that it is on its own line
        WriteStream(reqStream, "\n--" + Boundary + "--");
        WriteStream(reqStream, "\n");
        try
        {
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;

            if (response.StatusCode == HttpStatusCode.Created)
            {
                byte[] responseBytes = new byte[response.ContentLength];
                using (var reader = new System.IO.BinaryReader(response.GetResponseStream()))
                {
                    reader.Read(responseBytes, 0, responseBytes.Length);
                }
                string responseText = Encoding.UTF8.GetString(responseBytes);
                CreateEnvelopeResponse createEnvelopeResponse = new CreateEnvelopeResponse();

                createEnvelopeResponse = JsonConvert.DeserializeObject <CreateEnvelopeResponse>(responseText);
                if (createEnvelopeResponse.status.Equals("sent"))
                {
                    // Now that we have created the envelope, get the recipient token for the first signer
                    String url = Request.Url.AbsoluteUri;
                    RecipientViewRequest recipientViewRequest = new RecipientViewRequest();
                    recipientViewRequest.authenticationMethod = "email";
                    recipientViewRequest.clientUserId         = signer.clientUserId;
                    recipientViewRequest.email     = email.Value;
                    recipientViewRequest.returnUrl = url.Substring(0, url.LastIndexOf("/")) + "/ConfirmationScreen.aspx";
                    recipientViewRequest.userName  = firstname.Value + " " + lastname.Value;

                    HttpWebRequest request2 = HttpWebRequest.Create(ConfigurationManager.AppSettings["DocuSignServer"] + "/restapi/v2/accounts/" + ConfigurationManager.AppSettings["API.TemplatesAccountID"] + "/envelopes/" + createEnvelopeResponse.envelopeId + "/views/recipient") as HttpWebRequest;
                    request2.Method = "POST";

                    // Set the authenticationheader
                    request2.Headers["X-DocuSign-Authentication"] = GetSecurityHeader();

                    request2.Accept      = "application/json";
                    request2.ContentType = "application/json";

                    Stream reqStream2 = request2.GetRequestStream();

                    WriteStream(reqStream2, JsonConvert.SerializeObject(recipientViewRequest));
                    HttpWebResponse response2 = request2.GetResponse() as HttpWebResponse;

                    responseBytes = new byte[response2.ContentLength];
                    using (var reader = new System.IO.BinaryReader(response2.GetResponseStream()))
                    {
                        reader.Read(responseBytes, 0, responseBytes.Length);
                    }
                    string response2Text = Encoding.UTF8.GetString(responseBytes);

                    RecipientViewResponse recipientViewResponse = new RecipientViewResponse();
                    recipientViewResponse = JsonConvert.DeserializeObject <RecipientViewResponse>(response2Text);
                    Response.Redirect(recipientViewResponse.url);
                }
            }
        }
        catch (WebException ex)
        {
            if (ex.Status == WebExceptionStatus.ProtocolError)
            {
                HttpWebResponse response = (HttpWebResponse)ex.Response;
                using (var reader = new System.IO.StreamReader(ex.Response.GetResponseStream(), UTF8Encoding.UTF8))
                {
                    string       errorMess = reader.ReadToEnd();
                    log4net.ILog logger    = log4net.LogManager.GetLogger(typeof(KitchenSink));
                    logger.Info("\n----------------------------------------\n");
                    logger.Error("DocuSign Error: " + errorMess);
                    logger.Error(ex.StackTrace);
                    Response.Write(ex.Message);
                }
            }
            else
            {
                log4net.ILog logger = log4net.LogManager.GetLogger(typeof(KitchenSink));
                logger.Info("\n----------------------------------------\n");
                logger.Error("WebRequest Error: " + ex.Message);
                logger.Error(ex.StackTrace);
                Response.Write(ex.Message);
            }
        }
    }
示例#9
0
        /// <summary>
        /// Get the space name prefix.
        /// e.g. if the target space is ejp.spaces.live.com, the prefix would be "ejp"
        /// </summary>
        /// <returns>The prefix part of the spaces url</returns>
        internal string GetSpaceNamePrefix()
        {
            Authenticate();
            if (this.LastStatusCode == WlsBridgeStatusCode.AuthenticationError)
            {
                return("");
            }

            if (!string.IsNullOrEmpty(_liveSpaceUri))
            {
                if (_liveSpaceUri.StartsWith("http://"))
                {
                    _liveSpaceUri = _liveSpaceUri.Substring(("http://").Length);
                }
                //	pick up the first token.
                string   delimiter = "./";
                string[] tokens    = _liveSpaceUri.Split(delimiter.ToCharArray());
                if (tokens.Length > 1)
                {
                    return(tokens[0]);
                }
            }
            const string SPACES_ROOT = "http://cid-{0}.spaces.live.com/";

            string         targetUrl = string.Format(SPACES_ROOT, _userId.cId);
            HttpWebRequest request   = (HttpWebRequest)HttpWebRequest.Create(targetUrl);
            string         ticket    = "";

            //Get ticket for storage service.
            try
            {
                ticket = _userId.GetTicket("spaces.live.com", "MBI", true);
            }
            catch (WLLogOnException wlsEx)
            {
                if (wlsEx.FlowUrl != null)
                {
                    this.LastStatusMessage = wlsEx.ErrorString + "Please go to " +
                                             wlsEx.FlowUrl.AbsoluteUri + "to correct the condition that caused the error";
                }
                else
                {
                    this.LastStatusMessage = wlsEx.ErrorString;
                }

                this.LastStatusCode = WlsBridgeStatusCode.AuthenticationError;
                return(null);                   //	cannot continue
            }
            request.Headers.Add("Authorization", "WLID1.0 " + ticket);
            request.AllowAutoRedirect = false;
            request.UserAgent         = _userAgent;
            request.Pipelined         = false;
            request.ProtocolVersion   = HttpVersion.Version10;
            request.Method            = "GET";
            string spacePrefix = "";

            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string          rcode    = response.StatusCode.ToString();
                // rcode should be 302 (Found).
                Debug.WriteLine("responseCode = " + rcode);
                spacePrefix = response.GetResponseHeader("Location");
                //	intersted in the very 1st token only.
                string   delimiter = ".";
                string[] tokens    = spacePrefix.Split(delimiter.ToCharArray());
                if (tokens.Length > 0)
                {
                    spacePrefix = tokens[0];
                }
                int start = spacePrefix.IndexOf("//");
                if (start > 0)
                {
                    spacePrefix = spacePrefix.Substring(start + 2);
                }
            }
            catch (WebException)
            {
                this.LastStatusCode = WlsBridgeStatusCode.ConnectivityError;
            }

            this.LastStatusCode = WlsBridgeStatusCode.Idle;
            return(spacePrefix);
        }
    /// <summary>
    /// Gets a <see cref="System.Collections.Generic.Dictionary{string,object}"/> representing the contents of the syndicated feed.
    /// </summary>
    /// <param name="feedUrl">A <see cref="System.String"/> representing the URL of the feed.</param>
    /// <param name="detailPage">A <see cref="System.String"/> representing the Guid of the detail page. </param>
    /// <param name="cacheDuration">A <see cref="System.Int32"/> representing the length of time that the content of the RSS feed will be saved to cache.</param>
    /// <param name="message">A <see cref="System.Collections.Generic.Dictionary{string,object}"/> that will contain any error or alert messages that are returned.</param>
    /// <param name="isError">A <see cref="System.Boolean"/> that is <c>true</c> if an error has occurred, otherwise <c>false</c>.</param>
    /// <returns></returns>
    public static Dictionary <string, object> GetFeed(string feedUrl, string detailPage, int cacheDuration, ref Dictionary <string, string> message, ref bool isError)
    {
        Dictionary <string, object> feedDictionary = new Dictionary <string, object>();

        if (message == null)
        {
            message = new Dictionary <string, string>();
        }

        if (String.IsNullOrEmpty(feedUrl))
        {
            message.Add("Feed URL not provided.", "The RSS Feed URL has not been provided. Please update the \"RSS Feed URL\" attribute in the block settings.");
            return(feedDictionary);
        }
        if (!System.Text.RegularExpressions.Regex.IsMatch(feedUrl, @"^(http://|https://|)([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"))
        {
            message.Add("Feed URL not valid.", "The Feed URL is not formatted properly. Please verify the \"RSS Feed URL\" attribute in block settings.");
            isError = false;
            return(feedDictionary);
        }

        ObjectCache feedCache = RockMemoryCache.Default;

        if (feedCache[GetFeedCacheKey(feedUrl)] != null)
        {
            feedDictionary = (Dictionary <string, object>)feedCache[GetFeedCacheKey(feedUrl)];
        }
        else
        {
            XDocument feed = null;

            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(feedUrl);

            using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
            {
                if (resp.StatusCode == HttpStatusCode.OK)
                {
                    XmlReader feedReader = XmlReader.Create(resp.GetResponseStream());
                    feed = XDocument.Load(feedReader);

                    feedReader.Close();
                }
                else
                {
                    message.Add("Error loading feed.", string.Format("An error has occurred while loading the feed.  Status Code: {0} - {1}", (int)resp.StatusCode, resp.StatusDescription));
                    isError = true;
                }
            }

            if (feed != null)
            {
                string detailPageBaseUrl = string.Empty;
                int    detailPageID      = 0;

                if (!String.IsNullOrEmpty(detailPage))
                {
                    detailPageID = new Rock.Model.PageService(new Rock.Data.RockContext()).Get(new Guid(detailPage)).Id;

                    detailPageBaseUrl = new PageReference(detailPageID).BuildUrl();
                }

                if (detailPageID > 0)
                {
                    detailPageBaseUrl = new PageReference(detailPageID).BuildUrl();
                }

                Dictionary <string, XNamespace> namespaces = feed.Root.Attributes()
                                                             .Where(a => a.IsNamespaceDeclaration)
                                                             .GroupBy(a => a.Name.Namespace == XNamespace.None ? String.Empty : a.Name.LocalName,
                                                                      a => XNamespace.Get(a.Value))
                                                             .ToDictionary(g => g.Key, g => g.First());


                feedDictionary = BuildElementDictionary(feed.Elements().First(), namespaces);

                if (feedDictionary.Count == 1 && feedDictionary.First().Value.GetType() == typeof(Dictionary <string, object>))
                {
                    feedDictionary = (Dictionary <string, object>)feedDictionary.First().Value;
                }

                if (feedDictionary.ContainsKey("lastBuildDate"))
                {
                    feedDictionary["lastBuildDate"] = DateTimeOffset.Parse(feedDictionary["lastBuildDate"].ToString()).LocalDateTime;
                }

                if (feedDictionary.ContainsKey("updated"))
                {
                    feedDictionary["updated"] = DateTimeOffset.Parse(feedDictionary["updated"].ToString()).LocalDateTime;
                }

                if (feedDictionary.ContainsKey("item") || feedDictionary.ContainsKey("entry"))
                {
                    List <Dictionary <string, object> > articles = (List <Dictionary <string, object> >)feedDictionary.Where(x => x.Key == "item" || x.Key == "entry").FirstOrDefault().Value;

                    foreach (var article in articles)
                    {
                        string idEntry       = String.Empty;
                        string idEntryHashed = string.Empty;
                        if (article.ContainsKey("id"))
                        {
                            idEntry = article["id"].ToString();
                        }

                        if (article.ContainsKey("guid"))
                        {
                            if (article["guid"].GetType() == typeof(Dictionary <string, object>))
                            {
                                idEntry = ((Dictionary <string, object>)article["guid"])["value"].ToString();
                            }
                            else
                            {
                                idEntry = article["guid"].ToString();
                            }
                        }

                        if (!String.IsNullOrWhiteSpace(idEntry))
                        {
                            System.Security.Cryptography.HashAlgorithm hashAlgorithm = System.Security.Cryptography.SHA1.Create();
                            System.Text.StringBuilder sb = new System.Text.StringBuilder();
                            foreach (byte b in hashAlgorithm.ComputeHash(System.Text.Encoding.UTF8.GetBytes(idEntry)))
                            {
                                sb.Append(b.ToString("X2"));
                            }

                            idEntryHashed = sb.ToString();

                            Dictionary <string, string> queryString = new Dictionary <string, string>();
                            queryString.Add("feedItemId", idEntryHashed);

                            if (detailPageID > 0)
                            {
                                article.Add("detailPageUrl", new PageReference(detailPageID, 0, queryString).BuildUrl());
                            }

                            article.Add("articleHash", idEntryHashed);
                        }

                        if (article.ContainsKey("pubDate"))
                        {
                            article["pubDate"] = DateTimeOffset.Parse(article["pubDate"].ToString()).LocalDateTime;
                        }

                        if (article.ContainsKey("updated"))
                        {
                            article["updated"] = DateTimeOffset.Parse(article["updated"].ToString()).LocalDateTime;
                        }
                    }
                }

                if (!String.IsNullOrEmpty(detailPageBaseUrl))
                {
                    feedDictionary.Add("DetailPageBaseUrl", detailPageBaseUrl);
                }
            }

            if (feedDictionary != null)
            {
                feedCache.Set(GetFeedCacheKey(feedUrl), feedDictionary, DateTimeOffset.Now.AddMinutes(cacheDuration));
            }
        }

        return(feedDictionary);
    }
示例#11
0
        public void internalSend(RequestToCancel request)
        {
            if (log.isDebugEnabled())
            {
                log.debug("internalSend(" + request);
            }
            ByteBuffer requestDataBuffer = request.buf;

            bool isNegotiate = BNegotiate.isNegotiateMessage(requestDataBuffer);
            bool isJson      = isNegotiate || BMessageHeader.detectProtocol(requestDataBuffer) == BMessageHeader.MAGIC_JSON;

            String destUrl = url;

            // Negotiate?
            if (isNegotiate)
            {
                // Send a GET request and pass the negotate string as parameter

                String negoStr = Encoding.UTF8.GetString(requestDataBuffer.array(), requestDataBuffer.position(), requestDataBuffer.remaining());
                negoStr = System.Uri.EscapeDataString(negoStr);

                destUrl = makeUrl(getServletPathForNegotiationAndAuthentication(),
                                  new String[] { "negotiate", negoStr });
            }

            // Reverse request (long-poll) ?
            else if (request.requestDirection == ERequestDirection.REVERSE)
            {
                destUrl = makeUrl(getServletPathForReverseRequest(), null);
            }

            HttpWebRequest conn = (HttpWebRequest)HttpWebRequest.Create(destUrl);

            request.setConnection(conn);
            conn.Method = isNegotiate ? "GET" : "POST";
            conn.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

            // Content-Type for POST request
            if (!isNegotiate)
            {
                conn.ContentType = isJson ? "application/json" : "application/byps";
            }

            conn.Accept = "application/json, application/byps, text/plain, text/html";
            if ((this.flagsVal & BWireFlags.GZIP) != 0)
            {
                conn.Headers.Add("Accept-Encoding", "gzip");
            }

            applySession(conn);

            IAsyncResult asyncResult = null;

            if (isNegotiate)
            {
                asyncResult = conn.BeginGetResponse(new AsyncCallback(this.getResponseCallback), request);
            }
            else
            {
                asyncResult = conn.BeginGetRequestStream(new AsyncCallback(this.getRequestStreamCallback), request);
            }

            request.startTimeoutWatcher(conn, asyncResult, request.timeoutMillisRequest);

            if (log.isDebugEnabled())
            {
                log.debug(")internalSend");
            }
        }
示例#12
0
        private ApiResult PostUrl(string apiPath, string postData, WebHeaderCollection headers, string method, string contenttype, string p12certfile, string cerpassword)
        {
            string url = string.Format("https://{0}:{1}{2}", this.m_pltip, this.m_pltPort, apiPath);

            if (isHttp)
            {
                url = string.Format("http://{0}:{1}{2}", this.m_pltip, this.m_pltPort, apiPath);
            }
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
            ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
            HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(url);

            X509Certificate2 cerCaiShang = new X509Certificate2(p12certfile, cerpassword);

            if (!isHttp)
            {
                httpRequest.ClientCertificates.Add(cerCaiShang);
            }
            httpRequest.Method            = method;
            httpRequest.ContentType       = contenttype;
            httpRequest.Referer           = null;
            httpRequest.AllowAutoRedirect = true;
            httpRequest.UserAgent         = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
            httpRequest.Accept            = "*/*";
            for (int i = 0; i < headers.Count; i++)
            {
                for (int j = 0; j < headers.GetValues(i).Length; j++)
                {
                    httpRequest.Headers.Add(headers.Keys[i], headers.GetValues(i)[j]);
                }
            }

            if (isHttp)
            {
                httpRequest.ServicePoint.Expect100Continue = false;
            }
            //
            if (method != "GET")
            {
                Stream       requestStem = httpRequest.GetRequestStream();
                StreamWriter sw          = new StreamWriter(requestStem);
                sw.Write(postData);
                sw.Close();
            }


            HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();

            Stream receiveStream = httpResponse.GetResponseStream();

            string result = string.Empty;

            using (StreamReader sr = new StreamReader(receiveStream))
            {
                result = sr.ReadToEnd();
            }
            ApiResult r = new ApiResult();

            r.result     = result;
            r.statusCode = (int)httpResponse.StatusCode;

            return(r);
        }
        //sl-king
        //uri is for overload, since every table has its own OData uri

        /// <summary>
        /// Get an XML element containing data from the specified table + container combination,
        /// filtering according to the filter criteria specified by the caller.
        /// </summary>
        /// <param name="container">Alias of the container, pass null for all records.</param>
        /// <param name="tableName">EntitySet\Table name, pass null for all records.</param>
        /// <param name="filter">Filter criteria, in Azure Table Services query syntax.</param>
        /// <param name="pageSize">Number of rows to be fetched</param>
        /// <param name="nextPartitionKey">PartionKey to fetch next partion data</param>
        /// <param name="nextRowKey">RowKey to fetch row information</param>
        /// <returns>An XML element containing the results of the query.</returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="WebException"></exception>
        /// <exception cref="Exception"></exception>
        public override XElement GetData(string uri, string container, string tableName,
                                         string filter, int pageSize,
                                         string nextPartitionKey, string nextRowKey,
                                         int skip)
        {
            XElement xmlData = null;
            Uri      temp;

            try
            {
                Uri serviceUri = string.IsNullOrEmpty(uri) ?
                                 LoadServiceUri(uri, container, tableName, filter, pageSize, nextPartitionKey, nextRowKey, skip) :
                                 LoadServiceUri(uri, "", "", filter, pageSize, nextPartitionKey, nextRowKey, skip);
                temp = serviceUri;

                // Store the partitionkey and rowkey as prevpartitionkey and prevrowkey before getting new set of data.
                string currentPartitionKeyStr = string.Empty;
                string currentRowKeyStr       = string.Empty;
                if (!string.IsNullOrEmpty(nextPartitionKey))
                {
                    currentPartitionKeyStr = nextPartitionKey;
                }

                if (!string.IsNullOrEmpty(nextRowKey))
                {
                    currentRowKeyStr = nextRowKey;
                }

                string nextPartitionKeyStr = string.Empty;
                string nextRowKeyStr       = string.Empty;

                var webRequest     = HttpWebRequest.Create(serviceUri);
                var response       = webRequest.GetResponse();
                var responseStream = response.GetResponseStream();

                if (response.Headers[AzureResources.continuation_nextPartionKey] != null)
                {
                    nextPartitionKeyStr = response.Headers[AzureResources.continuation_nextPartionKey];
                }

                if (response.Headers[AzureResources.continuation_nextRowKey] != null)
                {
                    nextRowKeyStr = response.Headers[AzureResources.continuation_nextRowKey];
                }

                var feed = XElement.Load(XmlReader.Create(responseStream));

                //this is ugly, but OGDI feeds are different for different queries
                IEnumerable <XElement> propertiesElements;
                if (string.IsNullOrEmpty(container) && tableName == "AvailableEndpoints")
                {
                    propertiesElements = feed.Elements(XNamespace.Get(AzureResources.nsAtom) + "entry").Elements(XNamespace.Get(AzureResources.nsAtom) + "content").Elements(XNamespace.Get(AzureResources.nsMetadata) + "properties");
                }
                else
                if (!string.IsNullOrEmpty(container) && tableName == "$metadata")    //v1/sql/$metadata
                {
                    XNamespace edmx   = "http://schemas.microsoft.com/ado/2007/06/edmx";
                    XNamespace edm    = "http://schemas.microsoft.com/ado/2007/05/edm";
                    var        ds     = feed.Element(edmx + "DataServices");
                    var        schema = ds.Element(edm + "Schema");
                    propertiesElements = schema.Elements(edm + "EntityType");
                    propertiesElements = propertiesElements.Concat(schema.Elements(edm + "EntityContainer"));    //we also need this, EntityType and EntitySet may not be named identically + there may be namespaces involved
                }
                else
                //if (!string.IsNullOrEmpty(container) && string.IsNullOrEmpty(tableName))//v1/sql/
                if (!string.IsNullOrEmpty(container) && (container == "EntitySets" || container == "Metadata"))        //v1/sql/
                {
                    XNamespace app       = "http://www.w3.org/2007/app";
                    var        workspace = feed.Element(app + "workspace");
                    propertiesElements = workspace.Elements(app + "collection");
                }
                else
                if (!string.IsNullOrEmpty(container) && !string.IsNullOrEmpty(tableName))            //v1/sql/entityset
                {
                    XNamespace atom = "http://www.w3.org/2005/Atom";
                    propertiesElements = feed.Elements(atom + "entry");
                }
                else
                {
                    throw new Exception("Implement for other OGDI queries");
                }

                // Remove PartitionKey, RowKey, and Timestamp because we don't want users to focus on these.
                // They are required by Azure Table storage, but will most likely go away
                // when we move to SDS.
                propertiesElements.Elements(XNamespace.Get(AzureResources.nsDataServices) + "PartitionKey").Remove();
                propertiesElements.Elements(XNamespace.Get(AzureResources.nsDataServices) + "RowKey").Remove();
                propertiesElements.Elements(XNamespace.Get(AzureResources.nsDataServices) + "Timestamp").Remove();

                // XmlDataSource doesn't support namespaces well
                // http://www.hanselman.com/blog/PermaLink,guid,8147b263-24fc-498d-83d1-546f4dde3fc3.aspx
                // Therefore, we will return XML that doesn't have any
                XElement root = new XElement("Root", propertiesElements);
                root.Add(new XAttribute("tableName", tableName));
                root.Add(new XAttribute("currentPartitionKey", currentPartitionKeyStr));
                root.Add(new XAttribute("currentRowKey", currentRowKeyStr));
                root.Add(new XAttribute("nextPartitionKey", nextPartitionKeyStr));
                root.Add(new XAttribute("nextRowKey", nextRowKeyStr));
                xmlData = StripNamespaces(root);
            }
            catch (Exception ex)
            {
                throw (ex);
            }

            return(xmlData);
        }
示例#14
0
            /// <summary>
            /// Comprobar si una url no esta rota
            /// </summary>
            /// <param name="url">url a comprobar</param>
            /// <param name="timeout">tiempo de espera maximo en milisegundos</param>
            /// <returns></returns>
            public static bool IsLinkWorking(string url, int timeout)
            {
                try
                {
                    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                    request.Timeout           = timeout;
                    request.AllowAutoRedirect = false;
                    bool            retorno;
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    switch (response.StatusCode)
                    {
                    case HttpStatusCode.NonAuthoritativeInformation:
                    case HttpStatusCode.NoContent:
                    case HttpStatusCode.ResetContent:
                    case HttpStatusCode.PartialContent:
                    case HttpStatusCode.MultipleChoices:
                    case HttpStatusCode.MovedPermanently:
                    case HttpStatusCode.Found:
                    case HttpStatusCode.SeeOther:
                    case HttpStatusCode.NotModified:
                    case HttpStatusCode.UseProxy:
                    case HttpStatusCode.Unused:
                    case HttpStatusCode.TemporaryRedirect:
                    case HttpStatusCode.BadRequest:
                    case HttpStatusCode.Unauthorized:
                    case HttpStatusCode.PaymentRequired:
                    case HttpStatusCode.Forbidden:
                    case HttpStatusCode.NotFound:
                    case HttpStatusCode.MethodNotAllowed:
                    case HttpStatusCode.NotAcceptable:
                    case HttpStatusCode.ProxyAuthenticationRequired:
                    case HttpStatusCode.RequestTimeout:
                    case HttpStatusCode.Conflict:
                    case HttpStatusCode.Gone:
                    case HttpStatusCode.LengthRequired:
                    case HttpStatusCode.PreconditionFailed:
                    case HttpStatusCode.RequestEntityTooLarge:
                    case HttpStatusCode.RequestUriTooLong:
                    case HttpStatusCode.UnsupportedMediaType:
                    case HttpStatusCode.RequestedRangeNotSatisfiable:
                    case HttpStatusCode.ExpectationFailed:
                    case HttpStatusCode.UpgradeRequired:
                    case HttpStatusCode.InternalServerError:
                    case HttpStatusCode.NotImplemented:
                    case HttpStatusCode.BadGateway:
                    case HttpStatusCode.ServiceUnavailable:
                    case HttpStatusCode.GatewayTimeout:
                    case HttpStatusCode.HttpVersionNotSupported:
                        retorno = false;
                        break;

                    case HttpStatusCode.Continue:
                    case HttpStatusCode.SwitchingProtocols:
                    case HttpStatusCode.OK:
                    case HttpStatusCode.Created:
                    case HttpStatusCode.Accepted:
                        retorno = true;
                        break;

                    default:
                        retorno = false;
                        break;
                    }
                    response.Close();
                    return(retorno);
                }
                catch
                {
                    return(false);
                }
            }
示例#15
0
        public void TestPage(Uri root, Uri uri, Cookie cookie, out List <HtmlUri> links, out double ts)
        {
            DateTime start = DateTime.UtcNow;

            Console.Write("{0} (from {1}) ...", uri.PathAndQuery, root.PathAndQuery);

            CookieContainer cookies = null;

            if (cookie != null)
            {
                cookies = new CookieContainer();
                cookies.Add(cookie);
            }

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);

            if (cookies != null)
            {
                request.CookieContainer = cookies;
            }
            request.Method            = "GET";
            request.AllowAutoRedirect = true;

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream          s        = response.GetResponseStream();
            StreamReader    sr       = new StreamReader(s);

            string data = sr.ReadToEnd();

            Assert.IsTrue(response.StatusCode == HttpStatusCode.OK, string.Format("Response code was {0}", response.StatusCode));
            Assert.IsFalse(string.IsNullOrEmpty(data));

            ts = DateTime.UtcNow.Subtract(start).TotalSeconds;
            Console.Write("[{0} bytes][{1} sec.]", data.Length, ts.ToString("0.00"));

            Assert.IsTrue(data.Length > 0, "Downloaded file size is zero.");

            if (response.ContentType != "text/html; charset=utf-8")
            {
                Console.WriteLine("[ignore: {0}]", response.ContentType);
                links = new List <HtmlUri>();
                return;
            }

            // login page
            if (response.ResponseUri.PathAndQuery.Contains("DBlog/Login.aspx") && response.ResponseUri.PathAndQuery.Contains("access=denied"))
            {
                Console.WriteLine("[ignore: {0}]", uri.PathAndQuery);
                links = new List <HtmlUri>();
                return;
            }

            int error_start = data.IndexOf("<div id=\"ctl00_noticeMenu_panelNotice\" class=\"notice_error\"");

            if (error_start > 0)
            {
                int    error_end = data.IndexOf("</div>", error_start);
                string error     = data.Substring(error_start, error_end - error_start);
                Assert.IsTrue(error_start < 0, string.Format("{0}: error: {1}", uri, error));
            }

            links = HtmlUriExtractor.Extract(data, root);
            // Console.WriteLine("\tExtracted {0} links.", links.Count);

            Console.WriteLine("[done]");
        }
示例#16
0
        /// <summary>
        /// We need at least one photo album to populate arbitrary blog images...
        /// The album name is predefined as "Blog Images", which is the same name as LiveWriter uses.
        /// This method ensures the photo album exists already.
        /// </summary>
        public void EnsureAlbumExist()
        {
            Authenticate();
            if (this.LastStatusCode == WlsBridgeStatusCode.AuthenticationError)
            {
                return;
            }

            const string PHOTO_WEBDAV_ROOT = "https://storage.msn.com/mydata/myspace/spacefolder/photoalbums/";

            string         targetUrl = PHOTO_WEBDAV_ROOT;
            HttpWebRequest request   = (HttpWebRequest)HttpWebRequest.Create(targetUrl);
            string         ticket    = "";

            //Get ticket for storage service.
            try
            {
                ticket = _userId.GetTicket("storage.msn.com", "MBI", true);
            }
            catch (WLLogOnException wlsEx)
            {
                if (wlsEx.FlowUrl != null)
                {
                    this.LastStatusMessage = wlsEx.ErrorString + "Please go to " +
                                             wlsEx.FlowUrl.AbsoluteUri + "to correct the condition that caused the error";
                }
                else
                {
                    this.LastStatusMessage = wlsEx.ErrorString;
                }

                this.LastStatusCode = WlsBridgeStatusCode.AuthenticationError;
                return;                 //	cannot continue
            }
            request.Headers.Add("Authorization", "WLID1.0 " + ticket);
            request.AllowAutoRedirect = false;
            request.UserAgent         = _userAgent;
            request.Pipelined         = false;
            request.ProtocolVersion   = HttpVersion.Version11;
            request.Method            = "GET";
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string          rcode    = response.StatusCode.ToString();
                System.Diagnostics.Debug.WriteLine("responseCode = " + rcode);
                using (Stream stream = response.GetResponseStream())
                {
                    bool              folderExists = false;
                    XPathDocument     document     = new XPathDocument(stream);
                    XPathNavigator    navigator    = document.CreateNavigator();
                    XPathNodeIterator iterator     = navigator.Select("/Folder/Items/Folder/RelationshipName");
                    while (iterator.MoveNext())
                    {
                        string relationshipName = iterator.Current.Value;
                        if (string.Compare(relationshipName, _albumName, true) == 0)
                        {
                            folderExists = true;
                            break;
                        }
                    }

                    if (!folderExists)
                    {
                        MakeAlbum();
                        if (this.LastStatusCode == WlsBridgeStatusCode.AuthenticationError)
                        {
                            return;
                        }
                    }
                }
            }
            catch (WebException)
            {
                this.LastStatusCode = WlsBridgeStatusCode.ConnectivityError;
            }

            this.LastStatusCode = WlsBridgeStatusCode.Idle;
        }
示例#17
0
 protected virtual HttpWebRequest GetWebRequest(string url)
 {
     return((HttpWebRequest)HttpWebRequest.Create(new Uri(url)));
 }
示例#18
0
        /// <summary>
        /// Put a photo into "Blog Images" album.
        /// </summary>
        /// <param name="photoName">The name of photo (display name in Photo Album)</param>
        /// <param name="dataStream">MemoryStream, which represents actual picture (JPEG, PNG, or whatever)</param>
        /// <param name="contentType">image/png, image/jpeg, etc</param>
        /// <returns></returns>
        public string PutPhoto(string photoName, byte[] data, string contentType)
        {
            Authenticate();
            if (this.LastStatusCode == WlsBridgeStatusCode.AuthenticationError)
            {
                return("");
            }

            const string PHOTO_API_URL = "https://storage.msn.com/mydata/myspace/spacefolder/photoalbums/{0}/{1}";

            string         targetUrl = string.Format(PHOTO_API_URL, _albumName, photoName);
            HttpWebRequest request   = (HttpWebRequest)HttpWebRequest.Create(targetUrl);
            string         ticket    = "";

            //Get ticket for storage service.
            try
            {
                ticket = _userId.GetTicket("storage.msn.com", "MBI", true);
            }
            catch (WLLogOnException wlsEx)
            {
                if (wlsEx.FlowUrl != null)
                {
                    this.LastStatusMessage = wlsEx.ErrorString + "Please go to " +
                                             wlsEx.FlowUrl.AbsoluteUri + "to correct the condition that caused the error";
                }
                else
                {
                    this.LastStatusMessage = wlsEx.ErrorString;
                }

                this.LastStatusCode = WlsBridgeStatusCode.AuthenticationError;
                return(null);                   //	cannot continue
            }
            request.Headers.Add("Authorization", "WLID1.0 " + ticket);
            request.AllowAutoRedirect = false;
            request.UserAgent         = _userAgent;
            request.Pipelined         = false;
            request.ProtocolVersion   = HttpVersion.Version11;
            request.Method            = "PUT";
            request.ContentType       = contentType;       // e.g. "image/png"
            string location = "";

            try
            {
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(data, 0, data.Length);
                }

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string          rcode    = response.StatusCode.ToString();
                System.Diagnostics.Debug.WriteLine("responseCode = " + rcode);
                location = response.GetResponseHeader("Location");
            }
            catch (WebException)
            {
                this.LastStatusCode = WlsBridgeStatusCode.ConnectivityError;
            }
            catch (NullReferenceException)
            {
                this.LastStatusCode = WlsBridgeStatusCode.ConnectivityError;
            }

            this.LastStatusCode = WlsBridgeStatusCode.Idle;
            return(location);
        }
        public void FlakyPageCheck()
        {
            try
            {
                string       basicPageText   = null;
                const string DefaultPagePath = "http://metaautomation.net/FlakyPage.aspx";

                Check.Step("Get the basic web page", delegate
                {
                    HttpWebRequest webRequest = null;
                    HttpWebResponse response  = null;

                    Check.Step("Make a HttpWebRequest", delegate
                    {
                        webRequest = (HttpWebRequest)HttpWebRequest.Create(DefaultPagePath);
                    });

                    Check.Step("Get the HttpWebResponse", delegate
                    {
                        webRequest.Timeout = (int)Check.StepTimeout; // gets the timeout defined in the check artifact for this step
                        string httpStatus  = "No response.";         // default

                        try
                        {
                            response = (HttpWebResponse)webRequest.GetResponse();
                        }
                        catch (WebException webEx)
                        {
                            response = (HttpWebResponse)webEx.Response;
                            throw;
                        }
                        finally
                        {
                            if (response != null)
                            {
                                httpStatus = response.StatusCode.ToString();
                            }

                            Check.SetCustomDataCheckStep("HttpStatusCode", httpStatus);
                        }
                    });

                    Check.Step("Read the text of the page", delegate
                    {
                        Stream receiveStream = response.GetResponseStream();

                        if (receiveStream == null)
                        {
                            throw new CheckFailException("The response stream of the HttpWebResponse is null.");
                        }

                        StreamReader readResponse = new StreamReader(receiveStream, Encoding.UTF8);

                        try
                        {
                            basicPageText = readResponse.ReadToEnd();
                        }
                        catch (IOException ex)
                        {
                            throw new CheckFailException("Reading the response failed.", ex);
                        }

                        if (basicPageText == null)
                        {
                            throw new CheckFailException("Failed to read the stream of the HttpWebResponse is null.");
                        }
                        else if (basicPageText.Length == 0)
                        {
                            throw new CheckFailException("The response stream of the HttpWebResponse yielded zero characters.");
                        }

                        response.Close();
                        readResponse.Close();
                    });
                });

                Check.Step("Target verification step", delegate
                {
                    const string TargetString = "Pattern Language";

                    if (!basicPageText.Contains(TargetString))
                    {
                        Check.AddCheckFailData("page source", basicPageText);

                        throw new CheckFailException(string.Format("The search string '{0}' was not found on the page. Check for a screenshot and the 'page source' data element.", TargetString));
                    }
                });
            }
            catch (Exception ex)
            {
                Check.ReportFailureData(ex);
            }
        }
示例#20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        public HttpWebRequest CreateRequest(HttpRequestCommand command)
        {
            HttpWebRequest req = HttpWebRequest.Create(command.Url) as HttpWebRequest;
            var            cm  = command;

            if (this.CookieContainer != null)
            {
                req.CookieContainer = this.CookieContainer;
            }
            if (this.Credentials != null)
            {
                req.Credentials = this.Credentials;
            }
            req.Method                = cm.MethodName.ToString().ToUpper();
            req.Accept                = cm.Accept;
            req.ContentType           = cm.ContentType;
            req.UseDefaultCredentials = cm.UseDefaultCredentials;
#if !SILVERLIGHT && !Pcl
            if (cm.Proxy != null)
            {
                req.Proxy = cm.Proxy;
            }
#endif
#if !SILVERLIGHT && !NETFX_CORE && !Pcl
            if (cm.ContentLength > -1)
            {
                req.ContentLength = cm.ContentLength;
            }
            req.AllowAutoRedirect         = cm.AllowAutoRedirect;
            req.AllowWriteStreamBuffering = cm.AllowWriteStreamBuffering;
            req.AutomaticDecompression    = cm.AutomaticDecompression;
            req.Connection          = cm.Connection;
            req.ConnectionGroupName = cm.ConnectionGroupName;
            req.ContinueDelegate    = cm.ContinueDelegate;
            req.Expect          = cm.Expect;
            req.IfModifiedSince = cm.IfModifiedSince;
            req.KeepAlive       = cm.KeepAlive;
            req.MaximumAutomaticRedirections = cm.MaximumAutomaticRedirections;
            req.MaximumResponseHeadersLength = cm.MaximumResponseHeadersLength;
            req.MediaType        = cm.MediaType;
            req.Pipelined        = cm.Pipelined;
            req.PreAuthenticate  = cm.PreAuthenticate;
            req.ProtocolVersion  = cm.ProtocolVersion;
            req.ReadWriteTimeout = cm.ReadWriteTimeout;
            req.Referer          = cm.Referer;
            req.SendChunked      = cm.SendChunked;
            req.Timeout          = cm.Timeout;
            req.TransferEncoding = cm.TransferEncoding;
            req.UnsafeAuthenticatedConnectionSharing = cm.UnsafeAuthenticatedConnectionSharing;
            req.UserAgent = cm.UserAgent;
            req.ClientCertificates.AddRange(this.ClientCertificates);
#endif
#if !_Net_3_5 && !SILVERLIGHT && !NETFX_CORE && !Pcl
            req.Date = cm.Date;
            if (String.IsNullOrEmpty(cm.Host) == false)
            {
                req.Host = cm.Host;
            }
#endif
            foreach (String key in cm.Headers.AllKeys)
            {
                req.Headers[key] = cm.Headers[key];
            }
            this.OnHttpWebRequestCreated(new HttpWebRequestCreatedEventArgs(req));
            return(req);
        }
示例#21
0
        public string[] Request(string command, string parameter, string ip)
        {
            string[]        pageItems = null;
            HttpWebRequest  request   = null;
            HttpWebResponse response  = null;
            StreamReader    reader    = null;

            string[] pageContent = null;

            bool isQuery = (command.ToLower() == "querymusicdatabase" || command.ToLower() == "queryvideodatabase") ? true : false;

            string ipAddress = (ip == null) ? configuredIp : ip;

            parameter = (parameter == null) ? "" : parameter;
            command   = "?command=" + Uri.EscapeDataString(command);
            command  += (parameter == null || parameter == "") ? "" : "&parameter=" + Uri.EscapeDataString(parameter);
            string uri = "http://" + ipAddress + apiPath + command;

            //WriteToLog(uri);

            try
            {
                request         = (HttpWebRequest)HttpWebRequest.Create(uri);
                request.Method  = "GET";
                request.Timeout = connectionTimeout;
                if (xbmcUsername != "" && xbmcPassword != "")
                {
                    request.Credentials = new NetworkCredential(xbmcUsername, xbmcPassword);
                }
                response = (HttpWebResponse)request.GetResponse();
                reader   = new StreamReader(response.GetResponseStream(), Encoding.UTF8);

                if (isQuery)
                {
                    pageContent = reader.ReadToEnd().Replace("</field>", "").Replace("\n", "").Replace("<html>", "").Replace("</html>", "").Split(new string[] { "<field>" }, StringSplitOptions.None);
                }
                else
                {
                    pageContent = reader.ReadToEnd().Replace("\n", "").Replace("<html>", "").Replace("</html>", "").Split(new string[] { "<li>" }, StringSplitOptions.None);
                }

                if (pageContent != null)
                {
                    if (pageContent.Length > 1)
                    {
                        pageItems = new string[pageContent.Length - 1];

                        for (int x = 1; x < pageContent.Length; x++)
                        {
                            pageItems[x - 1] = pageContent[x];
                        }
                    }
                    else
                    {
                        pageItems    = new string[1];
                        pageItems[0] = pageContent[0];
                    }
                }
            }
            catch (WebException e)
            {
                WriteToLog(e.Message + " || " + uri);
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
                if (reader != null)
                {
                    reader.Close();
                }
            }

            if (pageItems != null)
            {
                string[] aFirstEntry = pageItems[0].Split(':');

                if (aFirstEntry == null)
                {
                    if (aFirstEntry[0] == "Error")
                    {
                        WriteToLog(DateTime.Now.ToString("dd.MM.yyyy hh:mm:ss") + " - ERROR: " + aFirstEntry[1] + " || " + uri);
                    }
                }
            }

            return(pageItems);
        }
示例#22
0
        /// <summary>
        /// Posts to WNS task.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <param name="title">The title.</param>
        /// <param name="message">The message.</param>
        /// <param name="extraDataAsCSV">The extra data as CSV.</param>
        /// <returns>Operation Result.</returns>
        private string PostToWNSTask(string uri, string title, string message, string extraDataAsCSV)
        {
            try
            {
                uri.GuardNullEmpty("Uri");
                title.GuardNullEmpty("Title");
                message.GuardNullEmpty("Message");
                Logging.DoLog(new LogEntry()
                {
                    MessageDetails = string.Format("Notification sending for uri {0} and title {1} and message {2} ", uri, title, message),
                    LogCategory    = LoggingCategory.Event,
                    LogPriority    = LogPriorityID.High,
                    LogEventType   = TraceEventType.Information,
                    ClassName      = MethodBase.GetCurrentMethod().DeclaringType.Name,
                    MethodName     = MethodBase.GetCurrentMethod().Name
                });
                this.xml = this.xml.Replace("PLACEHOLDER1", title);
                this.xml = this.xml.Replace("PLACEHOLDER2", message);
                this.xml = this.xml.Replace("PLACEHOLDER3", extraDataAsCSV);
                if (accessToken == null)
                {
                    accessToken = this.GetAccessToken(this.secret, this.sid);
                }

                byte[] contentInBytes = Encoding.UTF8.GetBytes(this.xml);

                HttpWebRequest request = HttpWebRequest.Create(uri) as HttpWebRequest;
                request.Method = "POST";
                request.Headers.Add("X-WNS-Type", NotificationType);
                request.ContentType = ContentType;
                request.Headers.Add("Authorization", string.Format("Bearer {0}", accessToken.AccessToken));

                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(contentInBytes, 0, contentInBytes.Length);
                }

                using (HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse())
                {
                    return(webResponse.StatusCode.ToString());
                }
            }
            catch (WebException webException)
            {
                Logging.DoLog(new LogEntry()
                {
                    MessageDetails = string.Format("Notification sending for uri {0} and title {1} and message {2} ", uri, title, message),
                    LogCategory    = LoggingCategory.Error,
                    LogPriority    = LogPriorityID.High,
                    LogEventType   = TraceEventType.Error,
                    ClassName      = MethodBase.GetCurrentMethod().DeclaringType.Name,
                    MethodName     = MethodBase.GetCurrentMethod().Name
                });
                if (webException.Response == null)
                {
                    return("Unknow Error");
                }

                HttpStatusCode status = ((HttpWebResponse)webException.Response).StatusCode;

                if (status == HttpStatusCode.Unauthorized)
                {
                    //// The access token you presented has expired. Get a new one and then try sending
                    //// your notification again.

                    //// Because your cached access token expires after 24 hours, you can expect to get
                    //// this response from WNS at least once a day.

                    this.GetAccessToken(this.secret, this.sid);

                    //// We recommend that you implement a maximum retry policy.
                    return(this.PostToWns(uri, title, message, extraDataAsCSV));
                }
                else if (status == HttpStatusCode.Gone || status == HttpStatusCode.NotFound)
                {
                    //// The channel URI is no longer valid.

                    //// Remove this channel from your database to prevent further attempts
                    //// to send notifications to it.

                    //// The next time that this user launches your app, request a new WNS channel.
                    //// Your app should detect that its channel has changed, which should trigger
                    //// the app to send the new channel URI to your app server.

                    return(string.Empty);
                }
                else if (status == HttpStatusCode.NotAcceptable)
                {
                    //// This channel is being throttled by WNS.

                    //// Implement a retry strategy that exponentially reduces the amount of
                    //// notifications being sent in order to prevent being throttled again.

                    //// Also, consider the scenarios that are causing your notifications to be throttled.
                    //// You will provide a richer user experience by limiting the notifications you send
                    //// to those that add true value.

                    return(string.Empty);
                }
                else
                {
                    //// WNS responded with a less common error. Log this error to assist in debugging.

                    //// You can see a full list of WNS response codes here:
                    //// http://msdn.microsoft.com/en-us/library/windows/apps/hh868245.aspx#wnsresponsecodes

                    string[] debugOutput =
                    {
                        status.ToString(),
                        webException.Response.Headers["X-WNS-Debug-Trace"],
                        webException.Response.Headers["X-WNS-Error-Description"],
                        webException.Response.Headers["X-WNS-Msg-ID"],
                        webException.Response.Headers["X-WNS-Status"]
                    };
                    return(string.Join(" | ", debugOutput));
                }
            }
            catch (Exception exception)
            {
                Logging.DoLog(new LogEntry()
                {
                    MessageDetails = exception.Message,
                    LogCategory    = LoggingCategory.Error,
                    LogPriority    = LogPriorityID.High,
                    LogEventType   = TraceEventType.Error,
                    ClassName      = MethodBase.GetCurrentMethod().DeclaringType.Name,
                    MethodName     = MethodBase.GetCurrentMethod().Name
                });

                return("EXCEPTION: " + exception.Message);
            }
        }
示例#23
0
        public XmlElement DoQueue()
        {
            if (_CallsQueue.Count == 0)
            {
                _IsMultiRequest = false;
                return(null);
            }

            DateTime startTime = DateTime.Now;

            this.Log("service url: [" + this._Config.ServiceUrl + "]");

            KalturaParams kparams = new KalturaParams();
            KalturaFiles  kfiles  = new KalturaFiles();

            // append the basic params
            kparams.Add("apiVersion", this._ApiVersion);
            kparams.Add("clientTag", this._Config.ClientTag);
            kparams.AddIntIfNotNull("format", this._Config.ServiceFormat.GetHashCode());

            string url = this._Config.ServiceUrl + "/api_v3/index.php?service=";

            if (_IsMultiRequest)
            {
                url += "multirequest";
                int i = 1;
                foreach (KalturaServiceActionCall call in _CallsQueue)
                {
                    KalturaParams callParams = call.GetParamsForMultiRequest(i);
                    kparams.Add(callParams);
                    KalturaFiles callFiles = call.GetFilesForMultiRequest(i);
                    kfiles.Add(callFiles);
                    i++;
                }

                // map params
                foreach (KeyValuePair <string, string> item in _MultiRequestParamsMap)
                {
                    string requestParam = item.Key;
                    string resultParam  = item.Value;

                    if (kparams.ContainsKey(requestParam))
                    {
                        kparams[requestParam] = resultParam;
                    }
                }
            }
            else
            {
                KalturaServiceActionCall call = _CallsQueue[0];
                url += call.Service + "&action=" + call.Action;
                kparams.Add(call.Params);
                kfiles.Add(call.Files);
            }

            // cleanup
            _CallsQueue.Clear();
            _IsMultiRequest = false;
            _MultiRequestParamsMap.Clear();

            kparams.Add("kalsig", this.Signature(kparams));

            this.Log("full reqeust url: [" + url + "]");

            // build request
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

            if (kfiles.Count == 0)
            {
                request.Timeout = _Config.Timeout;
            }
            else
            {
                request.Timeout = Timeout.Infinite;
            }
            request.Method = "POST";
            request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            request.Headers = _Config.RequestHeaders;

            // Add proxy information if required
            createProxy(request, _Config);

            if (kfiles.Count > 0)
            {
                this.PostMultiPartWithFiles(request, kparams, kfiles);
            }
            else
            {
                this.PostUrlEncodedParams(request, kparams);
            }

            // get the response
            WebResponse  response       = request.GetResponse();
            Encoding     enc            = System.Text.Encoding.UTF8;
            StreamReader responseStream = new StreamReader(response.GetResponseStream(), enc);
            string       responseString = responseStream.ReadToEnd();

            this._ResponseHeaders = response.Headers;
            string serverName    = null;
            string serverSession = null;

            for (int i = 0; i < this._ResponseHeaders.Count; ++i)
            {
                if (this._ResponseHeaders.Keys[i] == "X-Me")
                {
                    serverName = this._ResponseHeaders[i];
                }
                if (this._ResponseHeaders.Keys[i] == "X-Kaltura-Session")
                {
                    serverSession = this._ResponseHeaders[i];
                }
            }
            if (serverName != null || serverSession != null)
            {
                this.Log("server: [" + serverName + "], session: [" + serverSession + "]");
            }

            this.Log("result (serialized): " + responseString);

            DateTime endTime = DateTime.Now;

            this.Log("execution time for [" + url + "]: [" + (endTime - startTime).ToString() + "]");

            XmlDocument xml = new XmlDocument();

            xml.LoadXml(responseString);

            this.ValidateXmlResult(xml);
            XmlElement result = xml["xml"]["result"];

            this.ThrowExceptionOnAPIError(result);

            return(result);
        }
        public async void DownloadAction()
        {
            Progress <DownloadOperation> progress = null;

            if (Url == null || Url == "")
            {
                ContentDialog notFoundLinkFileDialog = new ContentDialog()
                {
                    Title             = resourceMap.GetValue("titleErrorDownloadFileDialog", resourceContext).ValueAsString,
                    Content           = resourceMap.GetValue("contentErrorDownloadFileDialog", resourceContext).ValueAsString,
                    PrimaryButtonText = "ОК"
                };
                ContentDialogResult result = await notFoundLinkFileDialog.ShowAsync();

                return;
            }
            FolderPicker folderPicker = new FolderPicker
            {
                SuggestedStartLocation = PickerLocationId.Downloads,
                ViewMode = PickerViewMode.Thumbnail
            };

            folderPicker.FileTypeFilter.Add("*");

            StorageFolder folder = await folderPicker.PickSingleFolderAsync();

            if (folder != null)
            {
                Uri         downloadUrl = new Uri(Url);
                String      fileName    = Path.GetFileName(downloadUrl.ToString());
                var         request     = HttpWebRequest.Create(downloadUrl) as HttpWebRequest;
                StorageFile file        = await folder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);

                downloadOperation = backgroundDownloader.CreateDownload(downloadUrl, file);
                progress          = new Progress <DownloadOperation>(x => ProgressChanged(downloadOperation));
                cancellationToken = new CancellationTokenSource();
                try
                {
                    DownloadFile newFile = new DownloadFile
                    {
                        Id   = downloadOperation.Guid,
                        Name = fileName
                    };
                    toastNotification.SendUpdatableToastWithProgress(newFile.Name);
                    newFile.FileSize    = (downloadOperation.Progress.TotalBytesToReceive / 1024).ToString() + " kb";
                    newFile.DateTime    = DateTime.Now;
                    newFile.Type        = FType;
                    newFile.Description = Description;
                    newFile.Status      = Status;
                    Files.Add(newFile);
                    await downloadOperation.StartAsync().AsTask(cancellationToken.Token, progress);

                    if (downloadOperation.Progress.Status == BackgroundTransferStatus.Completed)
                    {
                        toastNotification.SendCompletedToast(fileName);
                        dataStorage.Save(Files);
                        UpdateTileAction();
                    }
                    IsEnableButtons = false;
                    Url             = Description = "";
                    FType           = FileType.None;
                }
                catch (TaskCanceledException)
                {
                    Status = resourceMap.GetValue("canceledStatus", resourceContext).ValueAsString;
                    await downloadOperation.ResultFile.DeleteAsync();

                    downloadOperation = null;
                }
                catch (Exception)
                {
                    Status = "File not found";
                    var messageDialog = new MessageDialog("No internet connection has been found.");
                    await downloadOperation.ResultFile.DeleteAsync();

                    downloadOperation = null;
                }
            }
        }
示例#25
0
        void LoadEmoticons()
        {
            TwitchEmoticonResponse emotes = null;

            try
            {
                var req = (HttpWebRequest)HttpWebRequest.Create(@"https://api.twitch.tv/kraken/chat/emoticons");
                req.UserAgent = "WinterBot/0.0.1.0";
                var response   = req.GetResponse();
                var fromStream = response.GetResponseStream();

                StreamReader reader = new StreamReader(fromStream);
                string       data   = reader.ReadToEnd();

                emotes = JsonConvert.DeserializeObject <TwitchEmoticonResponse>(data);
            }
            catch (Exception e)
            {
                WinterBotSource.Log.TwitchWebApiError("emoticon", e.ToString());
                return;
            }

            List <TwitchEmoticon>         defaultSet = new List <TwitchEmoticon>();
            List <List <TwitchEmoticon> > imageSets  = new List <List <TwitchEmoticon> >(4096);

            foreach (var emote in emotes.emoticons)
            {
                foreach (var image in emote.images)
                {
                    if (image.emoticon_set == null)
                    {
                        defaultSet.Add(new TwitchEmoticon(m_cacheFolder, emote, image, true));
                    }
                    else
                    {
                        int setId = (int)image.emoticon_set;

                        Debug.Assert(setId <= 6000);
                        if (setId > 6000)
                        {
                            continue;
                        }

                        while (setId >= imageSets.Count)
                        {
                            imageSets.Add(null);
                        }

                        List <TwitchEmoticon> set = imageSets[setId];
                        if (set == null)
                        {
                            imageSets[setId] = set = new List <TwitchEmoticon>();
                        }

                        set.Add(new TwitchEmoticon(m_cacheFolder, emote, image, false));
                    }
                }
            }

            ImageSet = new TwitchImageSet(defaultSet, imageSets);
        }
示例#26
0
		public override void ExtendedSearch (TorrentUrl url)
		{
#if !NUnit
			Execute.Background(() =>
			{
#endif
				try
				{
					if (string.IsNullOrEmpty(url.InfoUrl))
					{
						throw new Exception("Could not find a URL to access this torrent's details.");	
					}
					
					HttpWebRequest request = HttpWebRequest.Create(url.InfoUrl) as HttpWebRequest;
					request.Timeout = Timeout;
					request.Method = WebRequestMethods.Http.Get;
					using (HttpWebResponse response = request.GetResponse () as HttpWebResponse)
					{
						using (Stream stream = response.GetResponseStream ())
						{
							TorrentUrlDetails details = new TorrentUrlDetails(url);
							
							HtmlDocument html = new HtmlDocument();
							html.Load(stream);
							
							var table = html.DocumentNode.SelectSingleNode("//th[@style='background-color: #EEEEEE;']/div/table");
							
							//Seeds and Peers
							string status = table.SelectSingleNode("//tr[3]/th[2]/font/b").InnerText;
							string[] split = status.Split('|');
							string seeds = _seedsRegex.Replace(split[0], string.Empty),
								peers = _peersRegex.Replace(split[1], string.Empty);
							
							details.Seeds = seeds.Replace(",", string.Empty).ToLong();
							details.Peers = peers.Replace(",", string.Empty).ToLong();
						
							//Date and user
							string torrentBy = table.SelectSingleNode("//tr[3]/th[4]/font/b").InnerText;
							split = _byRegex.Split(torrentBy);
							
							details.CreatedOn = split[0].ToDate();
							details.CreatedBy = HttpUtility.HtmlDecode(split[1]);
							
							//Comments
							var commentNodes = html.DocumentNode.SelectNodes("//div/table[@style='border-top: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000;']/tr/th");
							var comments = new List<Comment>();
							var comment = new Comment();
							for (int i = 1; i < commentNodes.Count; i++)
							{
								HtmlNode node = commentNodes[i];
								
								//User info, votes, etc.
								if (i % 2 == 1)
								{
									if (node.ChildNodes.Count < 6)
									{
										break;	
									}
									
									comment.User = HttpUtility.HtmlDecode(node.ChildNodes[1].InnerText).Trim();
									comment.UserInfo = HttpUtility.HtmlDecode(node.ChildNodes[3].InnerText).Trim();
									comment.CommentInfo = HttpUtility.HtmlDecode(node.ChildNodes[5].InnerText).Trim();
								}
								//Comment body
								else
								{
									comment.Text = HttpUtility.HtmlDecode(node.InnerText).Trim();
									comments.Add(comment);
									comment = new Comment();
								}
							}
							details.Comments = comments.ToArray();
							
							//Files
							details.Files = html.DocumentNode
								.SelectNodes("//table[@class='tor_details']/tr/th/font")
								.Select(n => new TorrentFile
									{
										Name = HttpUtility.HtmlDecode(_fileSizeRegex.Replace(n.InnerText, string.Empty)).Trim(),
										Size = HttpUtility.HtmlDecode(_fileSizeRegex.Match(n.InnerText).Groups[1].Value).Trim(),
									})
								.ToArray();
							
							OnExtendedSearchCompleted(new ExtendedSearchEventArgs(details));
						}
					}
				}
				catch (Exception exc)
				{
					OnExtendedSearchCompleted(new ExtendedSearchEventArgs(exc.Message));
				}
#if !NUnit
			});
#endif
		}
示例#27
0
        /// <summary>
        /// 建立请求,以模拟远程HTTP的POST请求方式构造并获取api的处理结果,带文件上传功能
        /// </summary>
        /// <param name="sParaTemp">请求参数数组</param>
        /// <param name="strMethod">提交方式。两个值可选:post、get</param>
        /// <param name="apiMethod">调用api的路径,例如登录“auth/login”</param>
        /// <param name="fileName">文件绝对路径</param>
        /// <param name="data">文件数据</param>
        /// <param name="contentType">文件内容类型</param>
        /// <param name="lengthFile">文件长度</param>
        /// <returns>支付宝处理结果</returns>
        public static string BuildRequest(Dictionary <string, string> sPara, string strMethod, string apiMethod, string fileName, byte[] data, string contentType, int lengthFile)
        {
            //构造请求地址
            string strUrl = GATEWAY_NEW + apiMethod;

            //设置HttpWebRequest基本信息
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(strUrl);

            //设置请求方式:get、post
            request.Method = strMethod;
            //设置boundaryValue
            string boundaryValue = DateTime.Now.Ticks.ToString("x");
            string boundary      = "--" + boundaryValue;

            request.ContentType = "\r\nmultipart/form-data; boundary=" + boundaryValue;
            //设置KeepAlive
            request.KeepAlive = true;
            //设置请求数据,拼接成字符串
            StringBuilder sbHtml = new StringBuilder();

            foreach (KeyValuePair <string, string> key in sPara)
            {
                sbHtml.Append(boundary + "\r\nContent-Disposition: form-data; name=\"" + key.Key + "\"\r\n\r\n" + key.Value + "\r\n");
            }
            sbHtml.Append(boundary + "\r\nContent-Disposition: form-data; name=\"withhold_file\"; filename=\"");
            sbHtml.Append(fileName);
            sbHtml.Append("\"\r\nContent-Type: " + contentType + "\r\n\r\n");
            string postHeader = sbHtml.ToString();
            //将请求数据字符串类型根据编码格式转换成字节流
            Encoding code = Encoding.GetEncoding(_input_charset);

            byte[] postHeaderBytes = code.GetBytes(postHeader);
            byte[] boundayBytes    = Encoding.ASCII.GetBytes("\r\n" + boundary + "--\r\n");
            //设置长度
            long length = postHeaderBytes.Length + lengthFile + boundayBytes.Length;

            request.ContentLength = length;

            //请求远程HTTP
            Stream requestStream = request.GetRequestStream();
            Stream myStream;

            try
            {
                //发送数据请求服务器
                requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                requestStream.Write(data, 0, lengthFile);
                requestStream.Write(boundayBytes, 0, boundayBytes.Length);
                HttpWebResponse HttpWResp = (HttpWebResponse)request.GetResponse();
                myStream = HttpWResp.GetResponseStream();
            }
            catch (WebException e)
            {
                return(e.ToString());
            }
            finally
            {
                if (requestStream != null)
                {
                    requestStream.Close();
                }
            }

            //读取api返回处理结果
            StreamReader  reader       = new StreamReader(myStream, code);
            StringBuilder responseData = new StringBuilder();

            String line;

            while ((line = reader.ReadLine()) != null)
            {
                responseData.Append(line);
            }
            myStream.Close();
            return(responseData.ToString());
        }
        /// <summary>
        /// Processes a message
        /// </summary>
        /// <param name="msg">The message being processed.</param>
        /// <param name="ctx">The context associated with the message.</param>
        /// <returns>The handling status for this operation.</returns>
        protected override ChainResult OnProcessOutputMessage(ref WsMessage msg, BindingContext ctx)
        {
            ArrayList props = ctx.BindingProperties;

            byte[] message     = null;
            string contentType = "text/plain";

            if (msg != null)
            {
                message = msg.Body as byte[];

                if (msg.BodyParts != null)
                {
                    contentType = "Multipart/Related;boundary=" +
                                  msg.MtomPropeties.boundary +
                                  ";type=\"application/xop+xml\";start=\"" +
                                  msg.MtomPropeties.start +
                                  "\";start-info=\"application/soap+xml\"";

                    ctx.BindingProperties.Add(new BindingProperty("header", HttpKnownHeaderNames.Server, "Microsoft-MF HTTP 1.0"));
                    ctx.BindingProperties.Add(new BindingProperty("header", HttpKnownHeaderNames.MimeVersion, "1.0"));
                    ctx.BindingProperties.Add(new BindingProperty("header", HttpKnownHeaderNames.Date, DateTime.Now.ToString()));
                }
                else
                {
                    contentType = "application/soap+xml; charset=utf-8";
                }
            }

            if (ctx is ClientBindingContext)
            {
                if (message == null)
                {
                    return(ChainResult.Abort);
                }

                HttpWebRequest request = HttpWebRequest.Create(new Uri(m_endpointUri.AbsoluteUri)) as HttpWebRequest;
                request.Timeout          = (int)(ctx.OpenTimeout.Ticks / TimeSpan.TicksPerMillisecond);
                request.ReadWriteTimeout = (int)(ctx.ReceiveTimeout.Ticks / TimeSpan.TicksPerMillisecond);

                ctx.ContextObject = request;

                // Post method
                request.Method = "POST";

                WebHeaderCollection headers = request.Headers;

                request.ContentType = contentType;
                request.UserAgent   = "MFWsAPI";

                request.Headers.Add(HttpKnownHeaderNames.CacheControl, "no-cache");
                request.Headers.Add(HttpKnownHeaderNames.Pragma, "no-cache");

                if (props != null)
                {
                    int len = props.Count;
                    for (int i = 0; i < len; i++)
                    {
                        BindingProperty prop      = (BindingProperty)props[i];
                        string          container = prop.Container;

                        if (container == "header")
                        {
                            headers.Add(prop.Name, (string)prop.Value);
                        }
                        else if (container == null || container == "")
                        {
                            string name = prop.Name;

                            if (name == HttpKnownHeaderNames.ContentType)
                            {
                                request.ContentType = (string)prop.Value;
                            }
                            else if (name == HttpKnownHeaderNames.UserAgent)
                            {
                                request.UserAgent = (string)prop.Value;
                            }
                        }
                    }
                }

                if (message != null)
                {
                    System.Ext.Console.Write("Http message sent: ");
                    System.Ext.Console.Write(message);

                    request.ContentLength = message.Length;

                    using (Stream stream = request.GetRequestStream())
                    {
                        // Write soap message
                        stream.Write(message, 0, message.Length);

                        // Flush the stream and force a write
                        stream.Flush();
                    }
                }
            }
            else
            {
                HttpListenerContext listenerContext = ctx.ContextObject as HttpListenerContext;

                if (listenerContext == null)
                {
                    return(ChainResult.Abort);
                }

                HttpListenerResponse listenerResponse = listenerContext.Response;

                if (listenerResponse == null || listenerResponse.OutputStream == null)
                {
                    return(ChainResult.Abort);
                }

                try
                {
                    using (StreamWriter streamWriter = new StreamWriter(listenerResponse.OutputStream))
                    {
                        // Write Header, if message is null write accepted
                        if (message == null)
                        {
                            listenerResponse.StatusCode = 202;
                        }
                        else
                        {
                            listenerResponse.StatusCode = 200;
                        }

                        // Check to see it the hosted service is sending mtom
                        WebHeaderCollection headers = listenerResponse.Headers;

                        listenerResponse.ContentType = contentType;

                        bool isChunked = false;

                        if (props != null)
                        {
                            int len = props.Count;
                            for (int i = 0; i < len; i++)
                            {
                                BindingProperty prop      = (BindingProperty)props[i];
                                string          container = prop.Container;
                                string          name      = prop.Name;
                                string          value     = (string)prop.Value;

                                if (container == "header")
                                {
                                    if (!isChunked && name == HttpKnownHeaderNames.TransferEncoding && value.ToLower() == "chunked")
                                    {
                                        isChunked = true;
                                    }

                                    headers.Add(name, (string)prop.Value);
                                }
                                else if (container == null || container == "")
                                {
                                    if (name == HttpKnownHeaderNames.ContentType)
                                    {
                                        listenerResponse.ContentType = (string)prop.Value;
                                        System.Ext.Console.Write(HttpKnownHeaderNames.ContentType + ": " + listenerResponse.ContentType);
                                    }
                                }
                            }
                        }

                        // If chunked encoding is enabled write chunked message else write Content-Length
                        if (isChunked)
                        {
                            // Chunk message
                            int bufferIndex      = 0;
                            int chunkSize        = 0;
                            int defaultChunkSize = 0xff;
#if DEBUG
                            byte[] displayBuffer = new byte[defaultChunkSize];
#endif
                            while (bufferIndex < message.Length)
                            {
                                // Calculate chunk size and write to stream
                                chunkSize = message.Length - bufferIndex < defaultChunkSize ? message.Length - bufferIndex : defaultChunkSize;
                                streamWriter.WriteLine(chunkSize.ToString("{0:X}"));
                                System.Ext.Console.Write(chunkSize.ToString("{0:X}"));

                                // Write chunk
                                streamWriter.WriteBytes(message, bufferIndex, chunkSize);
                                streamWriter.WriteLine();
#if DEBUG
                                Array.Copy(message, bufferIndex, displayBuffer, 0, chunkSize);
                                System.Ext.Console.Write(displayBuffer, bufferIndex, chunkSize);
#endif

                                // Adjust buffer index
                                bufferIndex = bufferIndex + chunkSize;
                            }

                            // Write 0 length and blank line
                            streamWriter.WriteLine("0");
                            streamWriter.WriteLine();
                            System.Ext.Console.Write("0");
                            System.Ext.Console.Write("");
                        }
                        else
                        {
                            if (message == null)
                            {
                                listenerResponse.ContentLength64 = 0;
                            }
                            else
                            {
                                listenerResponse.ContentLength64 = message.Length;
                            }

                            System.Ext.Console.Write("Content Length: " + listenerResponse.ContentLength64);

                            // If an empty message is returned (i.e. oneway request response) don't send
                            if (message != null && message.Length > 0)
                            {
                                System.Ext.Console.Write(message);

                                // Write soap message
                                streamWriter.WriteBytes(message, 0, message.Length);
                            }
                        }

                        // Flush the stream and return
                        streamWriter.Flush();
                    }
                }
                catch
                {
                    return(ChainResult.Abort);
                }
                finally
                {
                    listenerContext.Close();
                }
            }
            return(ChainResult.Handled);
        }
示例#29
0
        private bool InstallArchive(Archive archive)
        {
            long pos;
            int  retry = 0;

            while (retry < 3)
            {
                pos = 0;

                try {
                    Console.WriteLine("Installing " + archive.Path + "...");

                    Dictionary <string, ArchiveFile> targets = new Dictionary <string, ArchiveFile>();

                    foreach (ArchiveFile af in archive.Files)
                    {
                        if (!af.Deleted)
                        {
                            targets.Add(af.Src, af);
                        }
                    }

                    Console.WriteLine("Downloading from " + archive.URL);
                    HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(archive.URL);
                    req.Timeout = 60000;

                    using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
                        using (Stream responseStream = resp.GetResponseStream())
                            using (PositionedStream ps = new PositionedStream(responseStream))
                                using (ZipStreamFilter zsf = new ZipStreamFilter(ps))
                                    using (ZipInputStream zis = new ZipInputStream(zsf))
                                    {
                                        foreach (ZipStreamEntry entry in zis.Entries)
                                        {
                                            if (!targets.ContainsKey(entry.FileName))
                                            {
                                                continue;
                                            }

                                            ArchiveFile af = targets[entry.FileName];
                                            targets.Remove(entry.FileName);

                                            string dstFile = Configuration.Instance.FilePath(af.Dst);
                                            string dstPath = dstFile.Substring(0, dstFile.LastIndexOf(Path.DirectorySeparatorChar));
                                            Directory.CreateDirectory(dstPath);

                                            if (af.SHA1 == null && File.Exists(dstFile))
                                            {
                                                Console.WriteLine("Skipping {0} because no hash and file exists...", af.Dst);
                                                continue;
                                            }

                                            Console.WriteLine("Extracting {0}...", af.Dst);

                                            using (FileStream fs = new FileStream(dstFile + ".part", FileMode.Create))
                                                using (BufferedStream bs = new BufferedStream(fs))
                                                {
                                                    byte[] buf = new byte[4096];
                                                    int    i;
                                                    while ((i = zis.Read(buf, 0, buf.Length)) > 0)
                                                    {
                                                        bs.Write(buf, 0, i);
                                                        long inc = ps.Position - pos;
                                                        pos            += inc;
                                                        _totalPosition += inc;

                                                        UpdateStatus();
                                                    }
                                                }

                                            if (File.Exists(dstFile))
                                            {
                                                File.Delete(dstFile);
                                            }

                                            File.Move(dstFile + ".part", dstFile);

                                            // skip rest of this archive if we can
                                            if (targets.Count == 0)
                                            {
                                                break;
                                            }
                                        }

                                        responseStream.Close();
                                        resp.Close();

                                        UpdateStatus(true);
                                    }

                    break;
                } catch (Exception e) {
                    _totalPosition -= pos;
                    UpdateStatus(true);

                    if (++retry == 3)
                    {
                        Console.WriteLine(e.ToString(), e.Message);
                        return(false);
                    }
                    else
                    {
                        Console.WriteLine("Archive install failed, retrying...");
                    }
                }
            }

            return(true);
        }
示例#30
0
        private bool SetMethod(string sPage, string[] sPostData, string sReferer)
        {
            bool            bReturn             = false;
            HttpWebRequest  req                 = default(HttpWebRequest);
            HttpWebResponse resp                = default(HttpWebResponse);
            string          sPostDataValue      = "";
            Int32           nInitialCookieCount = 0;

            try
            {
                req           = (HttpWebRequest)HttpWebRequest.Create(sPage);
                req.Method    = "POST";
                req.UserAgent = sUserAgent;
                req.Accept    = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                req.Headers.Add("Accept-Language", "en-us,en;q=0.5");
                req.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
                req.Referer     = sReferer;
                req.ContentType = "application/x-www-form-urlencoded";
                req.Headers.Add("Keep-Alive", "300");
                if (oCookieCollection != null)
                {
                    // Pass cookie info from the login page
                    req.CookieContainer = SetCookieContainer(sPage);
                }
                if (sPostData.Count() % 2 == 0)
                {
                    // There is an even number of post names and values
                    for (Int32 i = 0; i <= sPostData.Count() - 1; i += 2)
                    {
                        // Put the post data together into one string
                        sPostDataValue += sPostData[i] + "=" + sPostData[i + 1] + "&";
                    }
                    sPostDataValue = sPostDataValue.Substring(0, sPostDataValue.Length - 1);                             // This will remove the extra "&" at the end that was added from the for loop above
                    // Post the data to the server
                    using (StreamWriter str = new StreamWriter(req.GetRequestStream()))
                    {
                        str.Write(sPostDataValue);
                        str.Close();
                    }
                    // Get the response
                    nInitialCookieCount = req.CookieContainer.Count;
                    resp = (HttpWebResponse)req.GetResponse();
                    if (req.CookieContainer.Count > nInitialCookieCount)
                    {
                        // Login successful
                        // Save new login cookies
                        SaveCookies(req.CookieContainer);
                        bReturn = true;
                        // At this point you are already logged in and cookies have been saved so any code after this is unnecessary unless you want to double-check the source code
                        resp = (HttpWebResponse)req.GetResponse();                                 // Get the response from the server
                        string sSourcePage = "";
                        using (StreamReader stw = new StreamReader(resp.GetResponseStream()))
                        {
                            sSourcePage = stw.ReadToEnd();                                     // Read the response from the server
                        }
                        System.IO.File.WriteAllText("testp.txt", sSourcePage);
                        System.Windows.Forms.MessageBox.Show("Loaded");
                        if (sSourcePage.Contains("<span style=\"color: #888\">Hi</span>"))
                        {
                            System.Windows.Forms.MessageBox.Show("Success");
                        }
                    }
                    else
                    {
                        MessageBox.Show("The email or password you entered are incorrect." + System.Environment.NewLine + System.Environment.NewLine + "Please try again.", "Unable to log in", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        bReturn = false;
                    }
                }
                else
                {
                    // Did not specify the correct amount of parameters so we cannot continue
                    MessageBox.Show("POST error.  Did not supply the correct amount of post data for " + sPage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    bReturn = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("POST error.  " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                bReturn = false;
            }
            return(bReturn);
        }