Exemplo n.º 1
0
 public SpywordsQueryWrapper(string login, string password, WebRequestHelper requestHelper)
 {
     _login = login;
     _password = password;
     _requestHelper = requestHelper;
     Authenticate();
 }
Exemplo n.º 2
0
 public GrayBlueOddTypeProvider(string targetOddTypeUrl, WebRequestHelper webRequestHelper, JavaScriptSerializer javaScriptSerializer, Func<object, object[]> toA, Func<object, Dictionary<string, object>> toD)
 {
     _targetOddTypeUrl = targetOddTypeUrl;
     _webRequestHelper = webRequestHelper;
     _javaScriptSerializer = javaScriptSerializer;
     _toA = toA;
     _toD = toD;
 }
Exemplo n.º 3
0
 static AlgoBase()
 {
     _webRequestHelper = BuildRequestHelper("CookiesSpyword", "spywords.ru", TimeSpan.FromSeconds(1));
     SpywordsQueryWrapper = new SpywordsQueryWrapper(
         SiteConfiguration.GetConfigurationProperty("spywordsLogin"),
         SiteConfiguration.GetConfigurationProperty("spywordsPassword"),
         _webRequestHelper
     );
 }
 public CollectSearchEngineDomainsFromPhrase()
     : base(TimeSpan.FromSeconds(30))
 {
     var interval = SiteConfiguration
         .GetConfigurationProperty<int>("SEInterval");
     interval = interval == default(int) ? 60 : interval;
     _yandexRequestHelper = BuildRequestHelper("CookiesYandex", "yandex.ru", TimeSpan.FromSeconds(interval));
     _googleRequestHelper = BuildRequestHelper("CookiesGoogle", "google.ru", TimeSpan.FromSeconds(interval));
 }
Exemplo n.º 5
0
        protected static T Browse <T>(string entity, string relatedEntity, string relatedEntityId, int limit, int offset, params string[] inc) where T : Entity
        {
            if (entity == null)
            {
                throw new ArgumentNullException(string.Format(Localization.Messages.RequiredAttributeException, "entity"));
            }

            return
                (WebRequestHelper.Get <T>(
                     WebRequestHelper.CreateBrowseTemplate(entity, relatedEntity, relatedEntityId, limit, offset,
                                                           CreateIncludeQuery(inc)), withoutMetadata: false));
        }
        public ActionResult DeleteMenuInfo()
        {
            int  menuID    = WebRequestHelper.GetIntFromParameters("MenuID");
            bool isSuccess = SystemMenuInfoBusiness.DeleteMenuInfo(menuID);

            ReturnInfoModel returnInfo = new ReturnInfoModel();

            returnInfo.IsSuccess = isSuccess;
            returnInfo.Message   = isSuccess ? "删除成功" : "删除失败";

            return(Json(returnInfo));
        }
Exemplo n.º 7
0
        public string DeleteMessage(string dataId)
        {
            var url = _visUrl + string.Format("/publishedMessage?dataId={0}", Uri.EscapeDataString(dataId ?? string.Empty));

            WebHeaderCollection headers = new WebHeaderCollection();

            headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");

            var response = WebRequestHelper.Delete(url, string.Empty, headers);

            return(response.HttpStatusCode.ToString() + " " + response.ErrorMessage + response.Body);
        }
Exemplo n.º 8
0
        public IList <PublishedMessageContract> GetPublishedMessages()
        {
            var url      = _visUrl + string.Format("/getPublishedMessages");
            var response = WebRequestHelper.Get(url);

            if (response.HttpStatusCode == HttpStatusCode.OK)
            {
                return(JsonConvert.DeserializeObject <List <PublishedMessageContract> >(response.Body));
            }

            return(new List <PublishedMessageContract>());
        }
Exemplo n.º 9
0
        public List <Notification> GetNotifications()
        {
            var url      = _visUrl + string.Format("/getNotification");
            var response = WebRequestHelper.Get(url);

            if (response.HttpStatusCode == HttpStatusCode.OK)
            {
                return(JsonConvert.DeserializeObject <List <Notification> >(response.Body));
            }

            return(null);
        }
Exemplo n.º 10
0
        public List <VisSubscriptionObject> GetSubscriptions(string dataId)
        {
            var url      = _visUrl + string.Format("/subscription?dataId={0}", Uri.EscapeDataString(dataId ?? string.Empty));
            var response = WebRequestHelper.Get(url);

            if (response.HttpStatusCode == HttpStatusCode.OK)
            {
                return(JsonConvert.DeserializeObject <List <VisSubscriptionObject> >(response.Body));
            }

            return(new List <VisSubscriptionObject>());
        }
Exemplo n.º 11
0
        protected static T Search <T>(string entity, string query, int limit = 25, int offset = 0, params string[] inc) where T : MetadataWrapper
        {
            if (query == null)
            {
                throw new ArgumentNullException(string.Format(Localization.Messages.RequiredAttributeException, "query"));
            }

            return
                (WebRequestHelper.Get <T>(
                     WebRequestHelper.CreateSearchTemplate(entity, query, limit, offset,
                                                           CreateIncludeQuery(inc)), withoutMetadata: false));
        }
Exemplo n.º 12
0
        public Model.CloudDisk.CloudFileInfoModel GetCloudFileInfo(string remotePath)
        {
            try
            {
                string           url    = "https://api.weipan.cn/2/metadata/sandbox";
                WebRequestHelper helper = new WebRequestHelper(url);
                var result           = helper.Get(url + remotePath + "?access_token=" + _accessToken);
                CloudFileInfoModel m = new CloudFileInfoModel();
                var fileInfo         = JsonHelper.DeserializeObject <SinaResponseFileInfoJsonEntity>(result);

                m.Bytes            = Convert.ToDouble(fileInfo.bytes);
                m.DiskType         = CloudDiskType.SINA;
                m.Path             = fileInfo.path;
                m.IsDir            = Convert.ToBoolean(fileInfo.is_dir);
                m.LastModifiedDate = Convert.ToDateTime(fileInfo.modified);
                m.MD5  = fileInfo.md5;
                m.SHA1 = fileInfo.sha1;
                if (fileInfo.contents != null)
                {
                    m.Contents = new List <CloudFileInfoModel>();
                    foreach (var oneDir in fileInfo.contents)
                    {
                        CloudFileInfoModel subDir = new CloudFileInfoModel();
                        subDir.Bytes            = Convert.ToDouble(oneDir.bytes);
                        subDir.Path             = oneDir.path;
                        subDir.IsDir            = Convert.ToBoolean(oneDir.is_dir);
                        subDir.LastModifiedDate = Convert.ToDateTime(oneDir.modified);
                        subDir.MD5  = oneDir.md5;
                        subDir.SHA1 = oneDir.sha1;

                        m.Contents.Add(subDir);
                    }
                }

                return(m);
            }
            catch (System.Net.WebException webEx)
            {
                HttpWebResponse errorResponse = webEx.Response as HttpWebResponse;
                if (errorResponse.StatusCode == HttpStatusCode.NotFound)
                {
                    //
                    return(null);
                }
                //webEx.Status == System.Net.WebExceptionStatus.CacheEntryNotFound
                //throw webEx;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(null);
        }
Exemplo n.º 13
0
        public void ResourcePackageLayoutFiles_DeleteLayoutFile_VerifyTemplateAndPageNotBasedToLayout()
        {
            int templatesCount = this.PageManager.GetTemplates().Count();

            try
            {
                FeatherServerOperations.ResourcePackages().AddNewResourcePackage(Constants.PackageResource);
                FeatherServerOperations.ResourcePackages().WaitForTemplatesCountToIncrease(templatesCount, 3);

                var template = this.PageManager.GetTemplates().Where(t => t.Title == Constants.TemplateTestLayout1).FirstOrDefault();

                if (template == null)
                {
                    throw new ArgumentException("template not found");
                }

                Guid pageId = FeatherServerOperations.Pages().CreatePageWithTemplate(template, Constants.PageTitle, Constants.PageUrl);

                var page    = this.PageManager.GetPageNode(pageId);
                var pageUrl = page.GetFullUrl();
                pageUrl = RouteHelper.GetAbsoluteUrl(pageUrl);

                var pageContent = WebRequestHelper.GetPageWebContent(pageUrl);
                Assert.IsTrue(pageContent.Contains(Constants.TestLayout1TemplateText), "Layout template text was not found in the page content");

                string filePath = FeatherServerOperations.ResourcePackages().GetResourcePackageDestinationFilePath(Constants.TestPackageName, Constants.TestLayoutFileName);
                File.Delete(filePath);

                template = this.PageManager.GetTemplates().Where(t => t.Title == Constants.TemplateTestLayout1).FirstOrDefault();
                Assert.IsNotNull(template, "Template was not found after layout file was deleted.");

                this.PublishPage(page);
                pageContent = WebRequestHelper.GetPageWebContent(pageUrl);

                Assert.IsFalse(pageContent.Contains(Constants.ServerErrorMessage), "Page throws a server error message");
                Assert.IsFalse(pageContent.Contains(Constants.TestLayout1TemplateText), "Layout template text was found in the page content");
            }
            finally
            {
                string[] templates = new string[] { Constants.TemplateTestLayout1, Constants.TemplateTestLayout2, Constants.TemplateTestLayout3 };

                ServerOperations.Pages().DeletePage(Constants.PageTitle);

                foreach (var template in templates)
                {
                    ServerOperations.Templates().DeletePageTemplate(template);
                }

                string path = FeatherServerOperations.ResourcePackages().GetResourcePackagesDestination(Constants.TestPackageName);
                Directory.Delete(path, true);
            }
        }
Exemplo n.º 14
0
        public void LayoutTemplates_EditLayoutFile_VerifyGeneratedTemplateAndCreatedPageContent()
        {
            PageManager pageManager    = PageManager.GetManager();
            int         templatesCount = pageManager.GetTemplates().Count();

            var folderPath = Path.Combine(this.SfPath, "MVC", "Views", "Layouts");

            try
            {
                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                }

                string filePath = Path.Combine(folderPath, LayoutFileName);

                FeatherServerOperations.ResourcePackages().AddNewResource(LayoutFileResource, filePath);

                FeatherServerOperations.ResourcePackages().WaitForTemplatesCountToIncrease(templatesCount, 1);

                var template = pageManager.GetTemplates().Where(t => t.Title == TemplateTitle).FirstOrDefault();
                Assert.IsNotNull(template, "Template was not found");

                Guid pageId = FeatherServerOperations.Pages().CreatePageWithTemplate(template, PageTitle, PageUrl);

                var page    = pageManager.GetPageNode(pageId);
                var pageUrl = page.GetFullUrl();
                pageUrl = RouteHelper.GetAbsoluteUrl(pageUrl);

                string pageContent = WebRequestHelper.GetPageWebContent(pageUrl);
                Assert.IsTrue(pageContent.Contains(LayoutTemplateText), "Layout template text was not found in the page content");

                string layoutFile = Path.Combine(folderPath, LayoutFileName);
                FeatherServerOperations.ResourcePackages().EditLayoutFile(layoutFile, TestLayoutTemplateText, TestLayoutTemplateTextEdited);

                Thread.Sleep(1000);

                pageContent = WebRequestHelper.GetPageWebContent(pageUrl);

                Assert.IsFalse(pageContent.Contains(ServerErrorMessage), "Page throws a server error message");
                Assert.IsFalse(pageContent.Contains(TestLayoutTemplateText), "Layout template text was found in the page content");
                Assert.IsTrue(pageContent.Contains(TestLayoutTemplateTextEdited), "New layout text was not found in the page content");
            }
            finally
            {
                ServerOperations.Pages().DeleteAllPages();
                ServerOperations.Templates().DeletePageTemplate(TemplateTitle);

                var filePath = Path.Combine(folderPath, LayoutFileName);
                File.Delete(filePath);
            }
        }
Exemplo n.º 15
0
        public async Task <List <Registro> > GetListRegistroByDate(DateTime date)
        {
            try
            {
                List <Registro> rg = new List <Registro>();

                dynamic httpContent = await WebRequestHelper.PostRequestAsync(
                    "http://biz6.samsungcsportal.com/gspn/operate.do", "numPerPage=&currPage=&"
                    + "IV_COMPANY=" + usuario.IV_COMPANY
                    + "&IV_EDATE=" + date.Date.ToString("yyyyMMdd")
                    + "&IV_JOBFLAG=1&IV_OBJECT_ID=&"
                    + "IV_ORG_CODE=" + usuario.GD_ASC_CODE
                    + "&IV_PARTNER=" + usuario.IV_GSPN_ID
                    + "&IV_REF_SO_NO="
                    + "&IV_SDATE=" + date.Date.ToString("yyyyMMdd")
                    + "&IV_STATUS="
                    + "&IV_SYMPTOM=&IV_REASON=&IV_IMEI=&IV_CONSUL=&IV_GSPNID=&cmd=ZifGspnConsulListCmd");

                dynamic dataRegistroDynamic = JObject.Parse(httpContent.result);

                if (dataRegistroDynamic == null || dataRegistroDynamic.EV_RET_MSG != "Success.")
                {
                    return(null);
                }

                foreach (var data in dataRegistroDynamic.eT_DETAIL)
                {
                    rg.Add(new Registro()
                    {
                        Id           = data.object_id,
                        DiagnosticGD = new Diagnostico {
                            consul = data.consul
                        },
                        Aparelho = new Aparelho()
                        {
                            Modelo = data.zzmodel
                        },
                        Cliente = new Cliente()
                        {
                            Id = data.zzconsumer, Nome = data.consumer_name
                        }
                    });
                }

                return(rg);
            }
            catch (Exception e)
            {
                new Exception();
                return(null);
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Main upload routine
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnUpload_Click(object sender, EventArgs e)
        {
            string phpCode = string.Empty;

            btnBrowse.Enabled    = false;
            btnUpload.Enabled    = false;
            richTextBox1.Enabled = false;

            if (EditingSelf)
            {
                if (!string.IsNullOrEmpty(richTextBox1.Text))
                {
                    phpCode = Helper.EncodeBase64ToString(richTextBox1.Text);
                }
                else
                {
                    LogHelper.AddShellLog(ShellUrl, "Attempted to upload empty file/data to self...", LogHelper.LOG_LEVEL.INFO);
                    btnUpload.Enabled = true;
                    return;
                }

                phpCode = PhpBuilder.WriteFileVar(PhpBuilder.phpServerScriptFileName, phpCode);
            }
            else
            {
                if (!string.IsNullOrEmpty(LocalFileLocation))
                {
                    phpCode = Convert.ToBase64String(File.ReadAllBytes(LocalFileLocation));
                }
                else if (!string.IsNullOrEmpty(richTextBox1.Text))
                {
                    phpCode = Helper.EncodeBase64ToString(richTextBox1.Text);
                }
                else
                {
                    LogHelper.AddShellLog(ShellUrl, "Attempted to upload empty file/data...", LogHelper.LOG_LEVEL.INFO);
                    btnUpload.Enabled = true;
                    return;
                }

                string remoteFileLocation = ServerPath + "/" + txtBoxFileName.Text;
                phpCode = PhpBuilder.WriteFile(remoteFileLocation, phpCode);
            }

            await WebRequestHelper.ExecuteRemotePHP(ShellUrl, phpCode);

            btnUpload.Enabled    = true;
            btnBrowse.Enabled    = true;
            richTextBox1.Enabled = true;

            this.Close();
        }
Exemplo n.º 17
0
        public NewsArticles GetNewsArticles(IEnumerable <KeyValuePair <string, string> > parameters)
        {
            NewsArticles newsArticles = null;
            NewsArticle  newsArticle  = null;

            if (parameters != null)
            {
                foreach (var keyValuePair in parameters)
                {
                    if (!string.IsNullOrWhiteSpace(keyValuePair.Key) && !string.IsNullOrWhiteSpace(keyValuePair.Value))
                    {
                        uri = UriHelper.AddParameter(uri, keyValuePair.Key, keyValuePair.Value);
                    }
                }
            }

            var rootobject = WebRequestHelper.JsonToObject <Rootobject>(uri);

            if (rootobject != null && rootobject.articles != null && rootobject.articles.Length > 0)
            {
                foreach (var article in rootobject.articles)
                {
                    if (newsArticles == null)
                    {
                        newsArticles = new NewsArticles()
                        {
                            TotalNewsArticles = rootobject.totalResults
                        };
                    }

                    if (newsArticles.SelectedNewsArticles == null)
                    {
                        newsArticles.SelectedNewsArticles = new Collection <NewsArticle>();
                    }

                    newsArticle = new NewsArticle
                    {
                        Author             = article.author,
                        DatePublished      = article.publishedAt,
                        Description        = article.description,
                        Image              = article.urlToImage,
                        Name               = article.title,
                        SourceOrganisation = article.source?.name,
                        Url = article.url
                    };

                    newsArticles.SelectedNewsArticles.Add(newsArticle);
                }
            }

            return(newsArticles);
        }
Exemplo n.º 18
0
        private string GetPageContent(Guid pageId)
        {
            PageManager pageManager = PageManager.GetManager();

            var page    = pageManager.GetPageNode(pageId);
            var pageUrl = page.GetFullUrl();

            pageUrl = RouteHelper.GetAbsoluteUrl(pageUrl);

            string pageContent = WebRequestHelper.GetPageWebContent(pageUrl);

            return(pageContent);
        }
Exemplo n.º 19
0
        public void Execute(object parameter)
        {
            var loadedEtities = parameter as ObservableCollection <LibraryEntityDTO>;

            if (loadedEtities != null)
            {
                var entityList = WebRequestHelper.GetAPI("https://localhost:44363/api/LibaryEntities/");
                foreach (var entity in entityList)
                {
                    loadedEtities.Add(entity);
                }
            }
        }
Exemplo n.º 20
0
        /****************************************************更新******************************************************/
        //进入预定页
        public void EnterSubmitPage(Action <string> callback, System.Net.CookieContainer cookie, string referer = "")
        {
            var webHelper = new WebRequestHelper(Properties.Resources.otn_submitOrderRequest, Properties.Resources.otn_leftTicket_init,
                                                 "POST", this._postdata, cookie);

            webHelper.SendDataToServer((str) =>
            {
                if (str != "")
                {
                    callback(str);
                }
            }, false, referer);
        }
Exemplo n.º 21
0
        //确认队列
        public void ConfirmSingleForQueue(Action <string> callback, System.Net.CookieContainer cookie)
        {
            var webHelper = new WebRequestHelper(Properties.Resources.otn_confirmSingleForQueue, Properties.Resources.otn_initDc,
                                                 "POST", this._postdata, cookie);

            webHelper.SendDataToServer((str) =>
            {
                if (str != "")
                {
                    callback(str);
                }
            });
        }
Exemplo n.º 22
0
        public string AuthorizeIdentities(string messageId, List <IdentityDescriptionObject> identities)
        {
            var url  = _visUrl + string.Format("/authorizeIdentities?dataId={0}", Uri.EscapeDataString(messageId));
            var json = JsonConvert.SerializeObject(identities, Formatting.Indented);

            WebHeaderCollection headers = new WebHeaderCollection();

            headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");

            var response = WebRequestHelper.Post(url, json, headers);

            return(response.HttpStatusCode.ToString() + " " + response.ErrorMessage + response.Body);
        }
Exemplo n.º 23
0
        public JsonReturn Post(string apiUrl, string postData, Encoding encoding, int tryNum = 1)
        {
            string responseMsg = WebRequestHelper.Post(apiUrl, postData, encoding, tryNum);

            if (responseMsg == null)
            {
                return(null);
            }
            else
            {
                return(JsonConvert.DeserializeObject <JsonReturn>(responseMsg));
            }
        }
Exemplo n.º 24
0
        private void SaveOpinionListToCdpm(DocumentInfo documentInfo, string opinionList)
        {
            //var url = CDPM_HOST + Opinion_SYNC_CDPM;
            var url = documentInfo.ExternalSaveOpinionUrl;

            var data = new
            {
                id          = documentInfo.ExternalID,
                opinionList = opinionList
            };

            WebRequestHelper.PostData(url, data);
        }
        public string SubmitUrl(string url)
        {
            WebRequestResult result = WebRequestHelper.SendRequest(url, 10000);

            if (result.IsSuccess)
            {
                return(result.ResponseText);
            }
            else
            {
                return(result.ErrorMessage);
            }
        }
Exemplo n.º 26
0
        public void NewsApiTest_Get()
        {
            var type = Apis.Material.Enums.MaterialType.voice;
            //aa5fe50648fb489a8083cdd203370470.jpg
            var result     = api.Get(type);
            var tempResult = (OtherMaterialResult)result;
            var wr         = new WebRequestHelper();

            if (!result.IsSuccess())
            {
                Assert.Fail("获取多图文信息失败,返回结果如下:" + result.DetailResult);
            }
        }
Exemplo n.º 27
0
        public string RemoveSubscription(string messageId, List <SpisSubscriptionObject> subscriptions)
        {
            var url  = _spisUrl + string.Format("/subscription?dataId={0}", Uri.EscapeDataString(messageId));
            var json = JsonConvert.SerializeObject(subscriptions, Formatting.Indented);

            WebHeaderCollection headers = new WebHeaderCollection();

            headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");

            var response = WebRequestHelper.Delete(url, json, headers);

            return(response.HttpStatusCode.ToString() + " " + response.ErrorMessage + response.Body);
        }
Exemplo n.º 28
0
        //验证订单
        public void CheckOrderInfo(Action <string> callback, System.Net.CookieContainer cookie)
        {
            var webrequest = new WebRequestHelper(Properties.Resources.otn_checkOrderInfo,
                                                  Properties.Resources.otn_initDc, "POST", _postdata, cookie);

            webrequest.SendDataToServer((str) =>
            {
                if (str != "")
                {
                    callback(str);
                }
            });
        }
Exemplo n.º 29
0
        public void ResourcePackageLayoutFiles_RenameTemplateBasedOnLayoutFile_VerifyTemplateAndPage()
        {
            int templatesCount = this.PageManager.GetTemplates().Count();

            try
            {
                FeatherServerOperations.ResourcePackages().AddNewResourcePackage(Constants.PackageResource);
                FeatherServerOperations.ResourcePackages().WaitForTemplatesCountToIncrease(templatesCount, 3);

                var template = this.PageManager.GetTemplates().Where(t => t.Title == Constants.TemplateTestLayout1).FirstOrDefault();

                if (template == null)
                {
                    throw new ArgumentException("template not found");
                }

                Guid pageId = FeatherServerOperations.Pages().CreatePageWithTemplate(template, Constants.PageTitle, Constants.PageUrl);

                var page    = this.PageManager.GetPageNode(pageId);
                var pageUrl = page.GetFullUrl();
                pageUrl = RouteHelper.GetAbsoluteUrl(pageUrl);

                var pageContent = WebRequestHelper.GetPageWebContent(pageUrl);
                Assert.IsTrue(pageContent.Contains(Constants.TestLayout1TemplateText), "Layout template text was not found in the page content");

                template.Title = Constants.TemplateRenamed;
                template.Name  = Constants.TemplateRenamed;
                this.pageManager.SaveChanges();

                Thread.Sleep(1000);

                pageContent = WebRequestHelper.GetPageWebContent(pageUrl);

                Assert.IsFalse(pageContent.Contains(Constants.ServerErrorMessage), "Page throws a server error message");
                Assert.IsFalse(pageContent.Contains(Constants.TestLayout1TemplateText), "Layout template text was found in the page content");
            }
            finally
            {
                string[] templates = new string[] { Constants.TemplateRenamed, Constants.TemplateTestLayout2, Constants.TemplateTestLayout3 };

                ServerOperations.Pages().DeleteAllPages();

                foreach (var template in templates)
                {
                    ServerOperations.Templates().DeletePageTemplate(template);
                }

                string path = FeatherServerOperations.ResourcePackages().GetResourcePackagesDestination(Constants.TestPackageName);
                FeatherServerOperations.ResourcePackages().DeleteDirectory(path);
            }
        }
        public static void StartInstance(Instance instance, int?timeout = null, string reason = null)
        {
            Assert.ArgumentNotNull(instance, "instance");

            string url = instance.GetUrl(@"/sitecore/service/keepalive.aspx?ts=" + DateTime.Now.Ticks + "&reason=" + (reason ?? "default"));

            Assert.IsNotNullOrEmpty(url, "url");
            try
            {
                WebRequestHelper.DownloadString(url, timeout);
            }
            catch (WebException ex)
            {
                string text        = "There is an issue with requesting '" + url + "'. ";
                var    webResponse = ex.Response;
                if (webResponse != null)
                {
                    using (var s = webResponse.GetResponseStream())
                    {
                        if (s != null)
                        {
                            using (StreamReader streamReader = new StreamReader(s))
                            {
                                text = streamReader.ReadToEnd();
                            }
                        }
                        else
                        {
                            text += "No error response stream provided.";
                        }
                    }
                }
                else
                {
                    text += "No error response provided.";
                }

                string text2 = string.Empty;
                try
                {
                    text2 = text.Substring(text.IndexOf("<title>") + "<title>".Length);
                    text2 = text2.Substring(0, text2.IndexOf("</title>"));
                }
                catch (Exception)
                {
                    text2 = text.Substring(0, Math.Min(text.Length, 200));
                }

                throw new WebException("{0} \r\nStatus: {1} \r\n{2}".FormatWith(ex.Message, ex.Status.ToString(), text2));
            }
        }
Exemplo n.º 31
0
        private async void Save_Click(object sender, RoutedEventArgs e)
        {
            if (ownerTxtBox.Text == "" || EmailTxtBox.Text == "" || subjectTxtbox.Text == "")
            {
                return;
            }

            string fName = "", lName = "";

            if (contactName.Text != "")
            {
                fName = contactName.Text.Split(' ')[0];
                lName = contactName.Text.Split(' ')[1];
            }

            string saveNewCaseURL = string.Concat(
                Properties.Settings.Default.ServerURL,
                "createSfObject.newcase?",
                "access_token=", Globals.ThisAddIn.myCredentials.AccessToken,
                $"&instance_url=https://ap4.salesforce.com&owner={ownerTxtBox.Text}",
                $"&contact={contactName.Text}",
                $"&account={accountName.Text}",
                $"&firstname={fName}",
                $"&lastname={lName}",
                $"&case_type={cbCaseType.Text}",
                $"&case_reason={cbReasonType.Text}",
                $"&status={cbStatusType.Text}",
                $"&priority={cbPriorityType.Text}",
                $"&case_origin={cbCaseOrigin.Text}",
                $"&form_subject={subjectTxtbox.Text}",
                $"&description={descTxtBox.Text}",
                $"&contact_email={EmailTxtBox.Text}",
                $"&searchcontactemail={contactEmail}",
                $"&searchaccountemail={accountEmail}"
                );



            string SaveCaseResponse = await WebRequestHelper.getResponseAsync(saveNewCaseURL);

            if (SaveCaseResponse != "")
            {
                try
                {
                    var apiResponse = JsonConvert.DeserializeObject <CreateCaseApiResponse>(SaveCaseResponse);
                    MessageBox.Show(apiResponse.Message);
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
                finally { onCancelClick?.Invoke(this, EventArgs.Empty); }
            }
        }
Exemplo n.º 32
0
 public BrowserWrapper(WebRequestHelper webRequestHelper, string proxy)
     : base(webRequestHelper)
 {
     _browserSender = BrowserCreator.BuildBrowser(_browserSettings = new BrowserSettings {
         WindowHeight = 1080,
         WindowWidth = 1920,
         Proxy = proxy
     });
     _currentTabs = new SimpleKangooCache<string, BrowserTab>(s => {
         var tab = _browserSender.GetNewTab();
         tab.OpenPage(s);
         return tab;
     });
 }
Exemplo n.º 33
0
        /// <summary>
        /// Gets the public page content.
        /// </summary>
        /// <param name="pageId">The id of the page.</param>
        /// <returns>The page content.</returns>
        public string GetPageContent(Guid pageId)
        {
            PageManager pageManager = PageManager.GetManager();

            var page    = pageManager.GetPageNode(pageId);
            var pageUrl = page.GetFullUrl(SystemManager.CurrentContext.AppSettings.DefaultFrontendLanguage, true);

            pageUrl = RouteHelper.GetAbsoluteUrl(pageUrl);
            pageUrl = UrlTransformations.AppendParam(pageUrl, "t", Guid.NewGuid().ToString());

            string pageContent = WebRequestHelper.GetPageWebContent(pageUrl);

            return(pageContent);
        }
Exemplo n.º 34
0
        public virtual void Staff()
        {
            var builder = new StringBuilder("name=1111");
            var sign    = GetSign("95c401f4824440bb9a10066c6c6499cf", builder.ToString());

            WebRequestHelper.SendPostRequest("http://dev.api.welfare.beeant.com/staff/index",
                                             new Dictionary <string, string>
            {
                { "name", "1111" },
                { "sign", sign },
                { "token", "95c401f4824440bb9a10066c6c6499cf" }
            });
            return;
        }
Exemplo n.º 35
0
        //TODO Move out to a service
        async void GetData()
        {
            var url = WebRequestHelper.BaseUrl + "?method=flickr.photos.search";

            var content = new Dictionary <string, string>
            {
                ["api_key"]        = "1ec450bec545d2e66304e349b78ce1c9",
                ["lat"]            = CurrentLat,
                ["lon"]            = CurrentLong,
                ["format"]         = "json",
                ["nojsoncallback"] = "1",
            };

            var response = await WebRequestHelper.MakeAsyncRequest(url, content);

            var json = response.Content.ReadAsStringAsync().Result;

            var apidata = JsonConvert.DeserializeObject <FlickerData>(json);

            if (apidata.stat == "ok")
            {
                for (int i = 1; i < 10; i++)
                {
                    i++;

                    var photo = apidata.photos.photo[i];

                    long id = long.Parse(photo.id);

                    string photoUrl     = "http://farm{0}.staticFlickr.com/{1}/{2}_{3}_n.jpg";
                    string baseFlickUrl = string.Format(photoUrl, photo.farm, photo.server, photo.id, photo.secret);

                    var bitmap = await Helpers.BitmapHelper.GetImageFromUrl(baseFlickUrl);

                    var flickrPhoto = new FlickrPhoto
                    {
                        ID       = id,
                        ImageURL = baseFlickUrl,
                        Title    = photo.title,
                        Image    = bitmap
                    };

                    _photos.Add(flickrPhoto);
                }

                Adapter.NotifyDataSetChanged();

                _progress.Hide();
            }
        }
Exemplo n.º 36
0
 public AppsWorldVisitorsParser(IEnumerable<Cookie> cookies, string referer)
 {
     var cookieContainer = new CookieContainer();
     cookies.Each(c => {
         cookieContainer.Add(c);
     });
     _webRequestHelper = new WebRequestHelper(null, cookieContainer) {
         MinRequestDelay = TimeSpan.FromSeconds(5)
     };
     _webRequestHelper.SetParam(WebRequestParamType.UserAgentString, new WebRequestParamString(referer));
     _webRequestHelper.SetParam(WebRequestParamType.AcceptString, new WebRequestParamString("application/json,application/javascript"));
     _webRequestHelper.SetParam(WebRequestParamType.ContentTypeString, new WebRequestParamString("application/json; charset=utf-8"));
     _webRequestHelper.SetParam(WebRequestParamType.HeadersArrayKeyValue,
         new WebRequestParamWebHeaderCollection(new WebHeaderCollection {
         })
     );
 }
Exemplo n.º 37
0
 public WebRequestWrapper(WebRequestHelper webRequestHelper)
 {
     RequestHelper = webRequestHelper;
 }
Exemplo n.º 38
0
 public WrDnmskWrapper(WebRequestHelper webRequestHelper)
     : base(webRequestHelper)
 {
 }