Exemple #1
0
      public PhoneListController(Scope _scope, Http _http)
      {
         what = "main";         

         /*
         http.Get("hello.html").Success((data,status)=> {
            Window.Alert(data.ToString());
         }).Error((data,status)=>{ 
            Window.Alert("errore!");
         });
         */

         var risp = _http.Get("data.json");

         risp.Success((data,status,header)=> 
         {            
            person = (JsDictionary) data;
           // Window.Alert(person["name"].ToString());
         });

         risp.Error((data,status)=>
         { 
         //   Window.Alert("errore!");
         });                
      }
Exemple #2
0
        public void Run(Http.IHttpListener listener, Http.ILogger logger)
        {

            /*
              TinyRestServerCSharp.TinyRest.Server()
                .WithLogger(new TinyRestServer.ConsoleLogger())
                .WithHttp()
                .WithPort(8001)
                .WithBasePath("/learning")
                .OnGetPath("/", (request, response) => "coucou " + (count++))
                .OnGetPath("/json", (request, response) => response.Json(new
                {
                    Text = "coucou " + (count++)
                }))
                .Create()
                .Listen();
             */

            listener.AddPrefix("http://+:8001");

            var routes = new List<Routing.HttpRoute>();
            
            new RoutesBuilder()
                .OnGetPath("/", (request, response) =>
                    {
                        return "coucou";
                    }
                );
            
        }
 internal virtual void ModifyRequest(Http.IHttpRequest request)
 {
     foreach (var header in HeadersToSet)
     {
         request.Headers[header.Key] = header.Value;
     }
 }
        public async Task RecordSessionAsync(Http.HttpRequest request, Http.HttpResponse response, TimeSpan duration)
        {
            int sessionId = -1;
            lock(this)
            {
                sessionId = nextSessionNumber++;
            }

            // Write client request
            var requestPart = this.outputPackage.CreatePart(UriForPart(sessionId, 'c'), "text/plain");
            using (var requestStream = requestPart.GetStream(System.IO.FileMode.Create))
            {
                await request.WriteToStreamAsync(requestStream);
            }

            var responsePart = this.outputPackage.CreatePart(UriForPart(sessionId, 's'), "text/plain");
            using (var responseStream = responsePart.GetStream(System.IO.FileMode.Create))
            {
                await response.WriteToStreamAsync(responseStream);
            }

            var metadataPart = this.outputPackage.CreatePart(UriForPart(sessionId, 'm'), "application/xml");
            var metadata = CreateMetadataForSession(sessionId, request.StartTime, duration);
            using (var metadataStream = metadataPart.GetStream(System.IO.FileMode.Create))
            {
                await metadata.WriteToStreamAsync(metadataStream);
            }
        }
 public static ISlumberConfiguration UseHttp(this ISlumberConfiguration configuration, Action<Http> configure = null)
 {
     configuration.UriEncoder = new DefaultUriEncoder(new HttpParameterEncoder());
     var http = new Http(configuration);
     configure?.Invoke(http);
     configuration.Http = http;
     return configuration;
 }
 public HttpRequestExpectation(Http method, string url, string body = null, NameValueCollection headers = null)
 {
     Method = method;
     Url = url;
     Body = body;
     Headers = new WebHeaderCollection();
     if (headers != null)
     {
         Headers.Add(headers);
     }
 }
        internal void FillParameters(Http httpContext, string path)
        {
            var values = regex.Match(path);
            foreach (var parameter in Parameters)
            {
                Log.Trace($"{parameter.Name}: {values.Groups[parameter.Name].Value}");
                parameter.Value = values.Groups[parameter.Name].Value;

                httpContext.Request.Query[parameter.Name] = parameter.Value;
            }
        }
Exemple #8
0
        private HttpExpectation Method(Http method, string url, string body = null, WebHeaderCollection expectedHeaders = null)
        {
            var httpExpectation = new HttpExpectation
            {
                Request = new HttpRequestExpectation(method, url, body, expectedHeaders)
            };

            Expectations.Add(httpExpectation);

            return httpExpectation;
        }
Exemple #9
0
        private HttpExpectation Method(Http method, string url, string body = null)
        {
            var httpExpectation = new HttpExpectation
            {
                Request = new HttpRequestExpectation(method, url, body)
            };

            Expectations.Add(httpExpectation);

            return httpExpectation;
        }
        public void Initialize()
        {
            try {
                var resp = new Http ().Get (
                    "http://api.stackoverflow.com/1.0/questions?tagged=monotouch");

                Data = Model.ParseQuestions (resp.Content, resp.ContentType);
                TableView.ReloadData ();
            }
            catch (Exception error)
            {
                DisplayError (error);
            }
        }
        public void MinimalisticAndFluent()
        {
            new Http().Get("url");

            new Http().Post("url");

            new Http().With().Content(new {});

            new Http().With().Headers((HttpContentHeaders headers) => { headers.Add("", new[] {""}); });

            new Http().With().Headers((HttpRequestHeaders headers) => { headers.Add("", new[] {""}); });

            new Http().With().Mime(Mime.AppJson);

            new Http().With().Mime("application/vnd.ms-excel");

            new Http().With().Timeout(TimeSpan.FromSeconds(3)).Head("");

            new Http().With().Version(new Version(1, 1)).Delete("");

            var r = new Http().With().Async().Get("").Result;

            new Http().With()
                .Settings(HttpSettings.SuppressNetworkExceptions | HttpSettings.SuppressSerializationExceptions);

            new Http().With().CancellationToken(new CancellationTokenSource().Token);

            new Http().With().Serializer(new BasicJsonSerializer()).Get("").As<object>();


            //Full on

            new Http().With()
                .Content(new TestType {Name="Sergej Popov", Age = 5})
                .Version(new Version(1, 1))
                .Timeout(TimeSpan.FromSeconds(30))
                .Serializer(new BasicJsonSerializer(new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat}))
                .Mime(Mime.AppJson)
                .Headers(headers => headers.ContentLanguage.Add("en-GB"))
                .CancellationToken(new CancellationTokenSource().Token)
                .Settings(HttpSettings.SuppressNetworkExceptions | HttpSettings.SuppressSerializationExceptions)
                .Post("http://idea-software.net")
                .As<TestType>();
        }
Exemple #12
0
 private static dynamic DynamicHttp()
 {
     dynamic http = new Http("http://localhost:8787");
     http.Trace = true;
     return http;
 }
 public TokenService(String baseUrl, Http http)
     : base(http)
 {
     _baseUrl = baseUrl;
 }
Exemple #14
0
        private string Query(string method, string function, Dictionary <string, string> param = null, bool auth = false, bool json = false)
        {
            //   lock (objLockQuery)
            {
                String[] proxys = System.Text.RegularExpressions.Regex.Split(Http.get("https://www.proxy-list.download/api/v1/get?type=https&anon=elite&country=CN"), Environment.NewLine);
                String   proxy  = proxys[new Random().Next(0, proxys.Length - 2)];

                string paramData = json ? BuildJSON(param) : BuildQueryData(param);
                string url       = "/api/v1" + function + ((method == "GET" && paramData != "") ? "?" + paramData : "");
                string postData  = (method != "GET") ? paramData : "";

                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(domain + url);
                webRequest.Method = method;
                WebProxy webProxy = new WebProxy(proxy.Split(':')[0], int.Parse(proxy.Split(':')[1]));
                //webRequest.Proxy = webProxy;

                if (auth)
                {
                    string nonce           = GetNonce().ToString();
                    string message         = method + url + nonce + postData;
                    byte[] signatureBytes  = hmacsha256(Encoding.UTF8.GetBytes(apiSecret), Encoding.UTF8.GetBytes(message));
                    string signatureString = ByteArrayToString(signatureBytes);

                    webRequest.Headers.Add("api-nonce", nonce);
                    webRequest.Headers.Add("api-key", apiKey);
                    webRequest.Headers.Add("api-signature", signatureString);
                }

                try
                {
                    if (postData != "")
                    {
                        webRequest.ContentType = json ? "application/json" : "application/x-www-form-urlencoded";
                        var data = Encoding.UTF8.GetBytes(postData);
                        using (var stream = webRequest.GetRequestStream())
                        {
                            stream.Write(data, 0, data.Length);
                        }
                    }

                    using (WebResponse webResponse = webRequest.GetResponse())
                        using (Stream str = webResponse.GetResponseStream())
                            using (StreamReader sr = new StreamReader(str))
                            {
                                return(sr.ReadToEnd());
                            }
                }
                catch (WebException wex)
                {
                    using (HttpWebResponse response = (HttpWebResponse)wex.Response)
                    {
                        if (response == null)
                        {
                            throw;
                        }

                        using (Stream str = response.GetResponseStream())
                        {
                            using (StreamReader sr = new StreamReader(str))
                            {
                                return(sr.ReadToEnd());
                            }
                        }
                    }
                }
            }
        }
Exemple #15
0
        public void LoginVerifyChilkat(ref Http http)
        {
            // Chilkat.Http http1 = new Chilkat.Http();
            // http1 = http;

            // ///Chilkat Http Request to be used in Http Post...
            // Chilkat.HttpRequest req = new Chilkat.HttpRequest();

            // bool success;

            // success = http.UnlockComponent("THEBACHttp_b3C9o9QvZQ06");
            // if (success != true)
            // {
            //     return;
            // }

            // ///Save Cookies...
            // http.CookieDir = "memory";
            // http.SendCookies = true;
            // http.SaveCookies = true;

            // string pageSource = http.QuickGetStr("http://www.facebook.com/login.php");
            // string valueLSD = "name=" + "\"lsd\"";
            // int startIndex = pageSource.IndexOf(valueLSD) + 18;
            // string value = pageSource.Substring(startIndex, 5);

            // ///Decode data as chilkat Request accepts only decoded data...
            // string charTest = "%E2%82%AC%2C%C2%B4%2C%E2%82%AC%2C%C2%B4%2C%E6%B0%B4%2C%D0%94%2C%D0%84";
            // string emailUser = Username.Split('@')[0] + "%40" + Username.Split('@')[1];
            // string DecodedCharTest = System.Web.HttpUtility.UrlDecode(charTest);
            // string DecodedEmail = System.Web.HttpUtility.UrlDecode(emailUser);

            // //  Build an HTTP POST Request:
            // req.UsePost();
            // //req.Path = "/login.php?login_attempt=1";

            // req.AddHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16");
            // //req.SetFromUrl("http://www.facebook.com/login.php?login_attempt=1");

            // req.AddParam("charset_test", DecodedCharTest);
            // req.AddParam("lsd", value);
            // req.AddParam("locale", "en_US");
            // req.AddParam("email", DecodedEmail);
            // req.AddParam("pass", Password);
            // req.AddParam("persistent", "1");
            // req.AddParam("default_persistent", "1");
            // req.AddParam("charset_test", DecodedCharTest);
            // req.AddParam("lsd", value);

            // Chilkat.HttpResponse respUsingPostURLEncoded = http.PostUrlEncoded("http://www.facebook.com/login.php?login_attempt=1", req);

            // if (respUsingPostURLEncoded == null)
            // {
            //     Thread.Sleep(1000);
            //     respUsingPostURLEncoded = http.PostUrlEncoded("http://www.facebook.com/login.php?login_attempt=1", req);
            // }
            // if (respUsingPostURLEncoded == null)
            // {
            //     return;
            // }

            // string ResponseLoginPostURLEncoded = respUsingPostURLEncoded.BodyStr;

            // string ResponseLogin = http.QuickGetStr("http://www.facebook.com/home.php");

            // if (ResponseLogin == null)
            // {
            //     Console.WriteLine("not login");
            // }

            // string ResponseConfirmed = http.QuickGetStr("http://www.facebook.com/?email_confirmed=1");
            //// http://www.facebook.com/desktop/notifier/transfer.php?__a=1
        }
 public void ResponseHeadersParsed(Http.HttpHeadersSummary headers)
 {
     this.Apply(i => i.ResponseHeadersParsed(headers));
 }
        protected override async Task OnInitializedAsync()
        {
            paradas = await Http.GetFromJsonAsync <List <Paradas> >("api/Paradas");

            await base.OnInitializedAsync();
        }
 protected override async Task OnInitAsync()
 {
     forecasts = await Http.GetJsonAsync <WeatherForecast[]>("api/SampleData/WeatherForecasts");
 }
Exemple #19
0
 public static Http c(string url)
 {
     Http hp = new Http(url);
     return hp;
 }
Exemple #20
0
        private List <Result> ResultForInstallPlugin(Query query)
        {
            List <Result> results    = new List <Result>();
            string        pluginName = query.SecondSearch;

            if (string.IsNullOrEmpty(pluginName))
            {
                return(results);
            }
            string json;

            try
            {
                json = Http.Get(pluginSearchUrl + pluginName, context.Proxy).Result;
            }
            catch (WebException e)
            {
                Log.Warn("Can't connect to Wox plugin website, check your conenction");
                Log.Exception(e);
                return(new List <Result>());
            }
            List <WoxPluginResult> searchedPlugins;

            try
            {
                searchedPlugins = JsonConvert.DeserializeObject <List <WoxPluginResult> >(json);
            }
            catch (JsonSerializationException e)
            {
                context.API.ShowMsg("Coundn't parse api search results", "Please update your Wox!", string.Empty);
                Log.Exception(e);
                return(results);
            }

            foreach (WoxPluginResult r in searchedPlugins)
            {
                WoxPluginResult r1 = r;
                results.Add(new Result
                {
                    Title    = r.name,
                    SubTitle = r.description,
                    IcoPath  = "Images\\plugin.png",
                    Action   = c =>
                    {
                        MessageBoxResult result = MessageBox.Show("Are your sure to install " + r.name + " plugin",
                                                                  "Install plugin", MessageBoxButton.YesNo);

                        if (result == MessageBoxResult.Yes)
                        {
                            string folder = Path.Combine(Path.GetTempPath(), "WoxPluginDownload");
                            if (!Directory.Exists(folder))
                            {
                                Directory.CreateDirectory(folder);
                            }
                            string filePath = Path.Combine(folder, Guid.NewGuid().ToString() + ".wox");

                            string pluginUrl = APIBASE + "/media/" + r1.plugin_file;

                            try
                            {
                                Http.Download(pluginUrl, filePath, context.Proxy);
                            }
                            catch (WebException e)
                            {
                                var info = "download plugin " + r.name + "failed.";
                                MessageBox.Show(info);
                                Log.Warn(info);
                                Log.Exception(e);
                                return(false);
                            }
                            context.API.InstallPlugin(filePath);
                        }
                        return(false);
                    }
                });
            }
            return(results);
        }
Exemple #21
0
        public static void Test_DebridLink_01()
        {
            //HttpRun.Load("https://api.debrid-link.fr/rest/token/1R6858wC6lO15X8i/new");
            string urlBase = "https://api.debrid-link.fr/rest/";
            //string login = RunSource.CurrentRunSource.Config.GetConfig("LocalConfig").GetExplicit("DownloadAutomateManager/DebridLink/Login");
            string login    = XmlConfig.CurrentConfig.GetConfig("LocalConfig").GetExplicit("DownloadAutomateManager/DebridLink/Login");
            string password = XmlConfig.CurrentConfig.GetConfig("LocalConfig").GetExplicit("DownloadAutomateManager/DebridLink/Password");
            //string publickey = "1R6858wC6lO15X8i";
            string publickey = XmlConfig.CurrentConfig.GetConfig("LocalConfig").GetExplicit("DownloadAutomateManager/DebridLink/PublicKey");
            //string sessidTime = "all";
            string sessidTime = XmlConfig.CurrentConfig.GetConfig("LocalConfig").GetExplicit("DownloadAutomateManager/DebridLink/SessidTime");
            string url        = urlBase + string.Format("token/{0}/new", publickey);
            HttpRequestParameters requestParameters = new HttpRequestParameters {
                Encoding = Encoding.UTF8
            };
            Http http = HttpManager.CurrentHttpManager.Load(new HttpRequest {
                Url = url
            }, requestParameters);
            DateTime dt = DateTime.Now;

            http.ResultText.zTraceJson();
            BsonDocument doc           = BsonSerializer.Deserialize <BsonDocument>(http.ResultText);
            string       token         = doc.zGet("value.token").zAsString();
            string       validTokenUrl = doc.zGet("value.validTokenUrl").zAsString();
            string       key           = doc.zGet("value.key").zAsString();
            int          ts            = doc.zGet("ts").zAsInt();

            Trace.WriteLine("request time   : \"{0:dd/MM/yyyy HH:mm:ss}\"", dt);
            Trace.WriteLine("result         : \"{0}\"", doc.zGet("result").zAsString());
            Trace.WriteLine("token          : \"{0}\"", token);
            Trace.WriteLine("validTokenUrl  : \"{0}\"", validTokenUrl);
            Trace.WriteLine("key            : \"{0}\"", key);
            Trace.WriteLine("ts             : \"{0}\"", ts);
            Trace.WriteLine("ts             : \"{0:dd/MM/yyyy HH:mm:ss}\"", zdate.UnixTimeStampToDateTime(ts));
            Trace.WriteLine("ts             : \"{0}\"", zdate.UnixTimeStampToDateTime(ts) - dt);

            // validTokenUrl : "https://secure.debrid-link.fr/user/2_2d481d8991e4db60f43d24d9d387b75699db7a0157182967/login"
            http = HttpManager.CurrentHttpManager.Load(new HttpRequest {
                Url = validTokenUrl
            }, requestParameters);

            // <script>if (window!=window.top) { top.location.href='https://secure.debrid-link.fr/login'; }</script>
            // <form action='' method='POST' class='form-horizontal'>
            // <input type='text' class='form-control' name='user'>
            // <input type='password' class='form-control' name='password'>
            // <input type='hidden' value='10_a3a206c4398f195283a4843d44f017f3211275e443747173' name='token'>
            // <input type='submit' style='display:none'>
            // <button type='submit' name='authorizedToken' value='1' class='btn btn-dl'>Envoyer</button>

            XXElement xeSource = http.zGetXDocument().zXXElement();

            // script : if (window!=window.top) { top.location.href='https://secure.debrid-link.fr/login'; }
            string script = xeSource.XPathValue("//head//script//text()");

            if (script == null)
            {
                Trace.WriteLine("//head//script not found");
                return;
            }
            Trace.WriteLine("script : \"{0}\"", script);
            Regex rg    = new Regex("top\\.location\\.href=[\"'](.*)[\"']", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
            Match match = rg.Match(script);

            if (!match.Success)
            {
                Trace.WriteLine("top.location.href='...' not found in script");
                return;
            }
            url = match.Groups[1].Value;
            Trace.WriteLine("login url : \"{0}\"", url);

            XXElement xeForm = xeSource.XPathElement("//form");
            string    action = xeForm.AttribValue("action");

            Trace.WriteLine("form action : \"{0}\"", action);
            if (action != null && action != "")
            {
                url = action;
            }
            HttpRequestMethod method = Http.GetHttpRequestMethod(xeForm.AttribValue("method"));

            Trace.WriteLine("form method : {0}", method);

            //XmlConfig localConfig = new XmlConfig(RunSource.CurrentRunSource.Config.GetExplicit("LocalConfig"));
            //string login = localConfig.GetExplicit("DownloadAutomateManager/DebridLink/Login");
            //string password = localConfig.GetExplicit("DownloadAutomateManager/DebridLink/Password");
            StringBuilder content = new StringBuilder();
            bool          first = true;
            string        name, value;

            //foreach (XXElement xe in xeForm.XPathElements(".//input"))
            foreach (XXElement xe in xeForm.DescendantFormItems())
            {
                name = xe.AttribValue("name");
                if (name == null)
                {
                    continue;
                }
                if (name == "user")
                {
                    value = login;
                }
                else if (name == "password")
                {
                    value = password;
                }
                else if (name == "sessidTime")
                {
                    value = sessidTime;
                }
                else
                {
                    value = xe.AttribValue("value");
                }
                if (!first)
                {
                    content.Append('&');
                }
                content.AppendFormat("{0}={1}", name, value);
                Trace.WriteLine("{0}={1}", name, value);
                first = false;
            }
            //XXElement xeButton = xeForm.XPathElement(".//button");
            //name = xeButton.AttribValue("name");
            //value = xeButton.AttribValue("value");
            //if (name != null && value != null)
            //{
            //    content.AppendFormat("&{0}={1}", name, value);
            //    Trace.WriteLine("{0}={1}", name, value);
            //}

            // "user=la_beuze&password=xxxxxx&sessidTime=all&token=10_56b51ee12ad5dabcac620230cda436cab94bd37154742765&authorizedToken=1"
            //  user=la_beuze&password=pbeuz0&sessidTime=all&token=10_3205776c76bb0479b1d57e9bf834b38ae2c5d10669848384&authorizedToken=1
            Trace.WriteLine("content : \"{0}\"", content.ToString());
            http = HttpManager.CurrentHttpManager.Load(new HttpRequest {
                Url = url, Method = method, Content = content.ToString()
            }, requestParameters);

            // <div class='panel-body'>
            // <div class='alert alert-success'>
            // La session a bien été activée. Vous pouvez utiliser l'application API Test
            // </div>
            // </div>
            xeSource = http.zGetXDocument().zXXElement();
            string loginMessage = xeSource.XPathValue("//div[@class='panel-body']//text()").Trim();

            Trace.WriteLine("login message : \"{0}\"", loginMessage);
        }
 public async Task searchProduct()
 {
     prodList = await Http.GetJsonAsync <Products[]>("/api/Product/Name/" + searchString);
 }
 protected override async Task OnInitAsync()
 {
     prodList = await Http.GetJsonAsync <Products[]>("/api/Product/");
 }
Exemple #24
0
        public void ScrapeRss(Feed specificFeed)
        {
            FeedList feeds;

            if (specificFeed == null)
            {
                feeds = FeedList.LoadByFeedType("RSS").Where(f => f.IsActive).ToList();
            }
            else
            {
                feeds = new FeedList();
                feeds.Add(specificFeed);
            }

            var runResult    = "";
            var xmlString    = "";
            var feedIsActive = true;

            foreach (var feed in feeds)
            {
                try {
                    string url = feed.FeedUrl;
                    xmlString = Http.Get(url);
                    //Web.WriteLine(xmlString);
                    //string profileImageUrl = "https://pbs.twimg.com/profile_images/2461203629/2kvvznykuqzo46kj6kec_normal.jpeg";
                    //string currentUserToken = "52e0eaf6e4b07e1b6390a5dc";  //mikes

                    var xml = bwbXml.Parse(xmlString);
                    foreach (var node in xml.Descendants("item"))
                    {
                        var uniqueStringValue = "rss:" + Crypto.CreateHash(node.ElementValue("guid") ?? node.ElementValue("link"));
                        var story             = FeedStory.LoadByUniqueString(uniqueStringValue);

                        if (story == null)
                        {
                            string link = node.ElementValue("link");

                            if (String.IsNullOrEmpty(link))
                            {
                                link = ExtractUrlFromHTML(node.ElementValue("description"));
                            }

                            var shortUrl = "";

                            if (!String.IsNullOrEmpty(link))
                            {
                                shortUrl = UrlShortenerController.UrlShortener.Create(link, "RSS Feed", true);
                            }

                            //string message = Fmt.TruncHTML(node.ElementValue("title").StripTags() + ". " + node.ElementValue("description").StripTags(), 130) + " " + shortUrl;

                            string message = node.ElementValue("title").StripTags() + ". " + node.ElementValue("description").StripTags();
                            message = (message.Length > 130 ? Fmt.TruncHTML(message, 130) + "..." : message) + " " + shortUrl;

                            //var imageUrl = node.ElementValue("enclosure");
                            story = new FeedStory();
                            story.UniqueString    = uniqueStringValue;
                            story.Title           = node.ElementValue("title");
                            story.Message         = message;
                            story.OriginalLinkUrl = node.ElementValue("link");
                            story.DateAdded       = node.ElementValue("pub-date").ConvertToDate(DateTime.Now);
                            story.Status          = "new";
                            story.AuthorName      = feed.Author.Name + (feed.Author.Via.IsNotBlank() ? " via " + feed.Author.Via : "");
                            story.FeedID          = feed.FeedID;
                            story.ProfileImageUrl = feed.Author.ProfilePicUrl;
                            story.Priority        = feed.DefaultPriority;
                            story.Save();
                            story.ApplyFilters();

                            // If it didn't match any filter and it's still null, get from the feed
                            if (story.Latitude == null || story.Longitude == null)
                            {
                                story.Latitude  = feed.Latitude;
                                story.Longitude = feed.Longitude;
                                story.Save();
                            }

                            Web.Write("<p><strong>Added new item as feed story (RSS Feed ID: " + feed.FeedID + ")</strong></p><p>" + message + "</p><hr/>");
                        }
                    }

                    runResult = "Success";
                } catch (Exception ex) {
                    Web.Write("<p><strong style='color:red'>Error! RSS Feed ID: " + feed.FeedID + "</strong></p><p>" + ex.Message + "</p><hr/>");
                    runResult = ex.Message;
                    //SendFeedErrorEmail(feed, ex);
                    //feedIsActive = false;
                    //SendEMail.SimpleSendHtmlEmail("*****@*****.**", "Herepin Feed error", "RSS Feed ID: " + feed.FeedID + "<br>"+ex.Message+"<br><br>" + xmlString);
                } finally {
                    feed.LastResult      = runResult;
                    feed.LastTimeRunning = DateTime.Now;
                    feed.IsActive        = feedIsActive;
                    feed.Save();
                }
            }
        }
 public static async Task <IResult> InvestBonus(long tbdId)
 {
     return(await Http.Get("/mgr/trans/b2c-details/" + tbdId + "/mer-xfer"));
 }
 protected override async Task OnInitAsync()
 {
     Console.WriteLine("User" + ThisUser.Usrnm);
     myOrders = await Http.GetJsonAsync <Orders[]>("/api/Orders/user/" + ThisUser.Usrnm);
 }
        // Проверка файла на наличие и соответствие
        private void CheckFile(string path, string adress)
        {
            Http downloader = new Http(worker);

            FileInfo file = new FileInfo(path);
            DirectoryInfo directory = file.Directory;

            if (directory.Exists)
                if (file.Exists)
                {
                    string hash = Hasher.GetSHA256(file);

                    // TODO сравнение хэша с хранящимся на сервере
                    if (hash != hash)
                        downloader.DownloadFile(adress, path);
                    else
                        worker.ReportProgress(0);
                }
                else
                    downloader.DownloadFile(adress, path);
            else
            {
                directory.Create();
                downloader.DownloadFile(adress, path);
            }
        }
        public async Task viewDetails(string prodId)
        {
            prod = await Http.GetJsonAsync <Products>("/api/Product/" + prodId);

            isView = true;
        }
Exemple #29
0
        /// <summary>
        /// 地方搜索
        /// </summary>
        /// <param name="userData">用户信息</param>
        /// <returns>返回信息</returns>
        private Hashtable[] funPlaceSearch(Hashtable userData)
        {
            moyu.Http myHttp = new Http();
            string url = "http://api.map.baidu.com/place/search";
            string parm = "?&query=" + userData["@body"].ToString().Substring(2);
            parm += "&key=d4597e2a57145c17dad7dc8ec4e20d58";
            parm += "&location=35.586056,104.626638&radius=10000";
            parm += "&output=xml";
            StreamReader reader = new StreamReader(myHttp.HttpGetAsStreamReader(url, parm).BaseStream);
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(reader);
            ArrayList myList = new ArrayList();

            XmlNode statusNode = xmlDoc.SelectSingleNode("/PlaceSearchResponse/status");
            if (statusNode.InnerText == "OK")
            {
                XmlNode results = xmlDoc.SelectSingleNode("/PlaceSearchResponse/results");
                foreach (XmlNode result in results)
                {
                    Hashtable theResult = new Hashtable();
                    foreach (XmlNode attr in result)
                    {
                        theResult[attr.Name] = attr.InnerText;
                        if (attr.Name == "location")
                        {
                            foreach (XmlNode pos in attr)
                            {
                                theResult[pos.Name] = pos.InnerText;
                            }
                        }
                    }
                    myList.Add(theResult);
                }
            }
            int count = myList.Count > 9 ? 9 : myList.Count;
            Hashtable[] rtItems = new Hashtable[count];
            for (var i = 0; i < count; i++)
            {
                Hashtable nowItem = (Hashtable)myList[i];
                rtItems[i] = new Hashtable();
                rtItems[i]["id"] = 0;
                rtItems[i]["messageType"] = 1;
                rtItems[i]["title"] = nowItem["name"].ToString() + "\n" + nowItem["address"];
                if (nowItem.ContainsKey("telephone"))
                {
                    rtItems[i]["title"] = rtItems[i]["title"].ToString() + "," + nowItem["telephone"].ToString();
                }
                rtItems[i]["body"] = nowItem["name"].ToString() +
                    "\n" + nowItem["address"].ToString();
                if (nowItem.ContainsKey("telephone"))
                {
                    rtItems[i]["body"] = rtItems[i]["body"].ToString() + "\n" + nowItem["telephone"].ToString();
                }
                rtItems[i]["picSmall"] =getPicUrl(false) ;
                rtItems[i]["picBig"] = getPicUrl(true);
                rtItems[i]["url"] = "http://www.ai0932.com/mobile/placeSearch.aspx?name=" + nowItem["name"]+
                    "&address=" + nowItem["address"] + "&lat=" + nowItem["lat"] + "&lng=" + nowItem["lng"]+
                    (nowItem.ContainsKey("telephone") ? ("&tel=" + nowItem["telephone"]) : "");
                rtItems[i]["orders"] = i;
            }
            return rtItems;
        }
Exemple #30
0
 protected override async Task OnInitAsync()
 {
     forecasts = await Http.GetJsonAsync <WeatherForecast[]>("sample-data/weather.json");
 }
Exemple #31
0
        public void CollectData()
        {
            //每个月5号,凌晨3点5分,采集数据
            if (DateTime.Now.Day == 5 && DateTime.Now.Hour == 3 && DateTime.Now.Minute == 5)
            {
                if (!iscollected)
                {
                    iscollected = true;
                    try
                    {
                        EventLogs.JobLog("开始作业-车型数据采集");
                        bool   hasnewdata             = false;
                        string urlBrand               = "http://sales.new4s.com/ajax/brand/1/";
                        string urlSeries              = "http://sales.new4s.com/ajax/brand/3/{0}/";
                        string urlModel               = "http://sales.new4s.com/ajax/brand/5/{0}/";
                        List <CarBrandInfo> listBrand = GetCarBrandList(true);

                        string           strBrand      = Http.GetPage(urlBrand, 3);
                        List <JsonModel> listJsonBrand = Serializer.DeserializeJson <List <JsonModel> >(strBrand);
                        if (listBrand == null)
                        {
                            listBrand = new List <CarBrandInfo>();
                        }
                        foreach (JsonModel jsonbrand in listJsonBrand)
                        {
                            int    brandid   = 0;
                            string brandname = jsonbrand.name.Replace(jsonbrand.fletter + "-", string.Empty);
                            if (!listBrand.Exists(l => l.Name == brandname))
                            {
                                brandid = AddCarBrand(new CarBrandInfo()
                                {
                                    Name      = brandname,
                                    NameIndex = jsonbrand.fletter
                                });
                            }
                            else
                            {
                                brandid = listBrand.Find(l => l.Name == brandname).ID;
                            }

                            if (brandid > 0)
                            {
                                List <CarSeriesInfo> listSeries = GetCarSeriesListByBrandID(brandid, true);
                                if (listSeries == null)
                                {
                                    listSeries = new List <CarSeriesInfo>();
                                }
                                string           strSeries      = Http.GetPage(string.Format(urlSeries, jsonbrand.id), 3);
                                List <JsonModel> listJsonSeries = Serializer.DeserializeJson <List <JsonModel> >(strSeries);
                                foreach (JsonModel jsonseries in listJsonSeries)
                                {
                                    int    seriesid   = 0;
                                    string seriesname = jsonseries.name;
                                    if (!listSeries.Exists(l => l.Name == seriesname))
                                    {
                                        seriesid = AddCarSeries(new CarSeriesInfo()
                                        {
                                            Name    = seriesname,
                                            BrandID = brandid
                                        });
                                    }
                                    else
                                    {
                                        seriesid = listSeries.Find(l => l.Name == seriesname).ID;
                                    }

                                    if (seriesid > 0)
                                    {
                                        List <CarModelInfo> listModel = GetCarModelListBySeriesID(seriesid, true);
                                        if (listModel == null)
                                        {
                                            listModel = new List <CarModelInfo>();
                                        }
                                        string           strModel      = Http.GetPage(string.Format(urlModel, jsonseries.id), 3);
                                        List <JsonModel> listJsonModel = Serializer.DeserializeJson <List <JsonModel> >(strModel);
                                        foreach (JsonModel jsonmodel in listJsonModel)
                                        {
                                            int    modelid   = 0;
                                            string modelname = jsonmodel.name;
                                            if (!listModel.Exists(l => l.Name == modelname))
                                            {
                                                modelid = AddCarModel(new CarModelInfo()
                                                {
                                                    Name     = modelname,
                                                    SeriesID = seriesid
                                                });
                                                hasnewdata = true;
                                            }
                                            else
                                            {
                                                modelid = listModel.Find(l => l.Name == modelname).ID;
                                            }

                                            if (modelid == 0)
                                            {
                                                throw new Exception("新增车型 " + modelname + " 出错");
                                            }
                                        }
                                    }
                                    else
                                    {
                                        throw new Exception("新增车系 " + seriesname + " 出错");
                                    }
                                }
                            }
                            else
                            {
                                throw new Exception("新增品牌 " + brandname + " 出错");
                            }
                        }

                        if (hasnewdata)
                        {
                            ReloadCarBrandListCache();
                            ReloadCarSeriesListCache();
                            ReloadCarModelListCache();
                        }
                        EventLogs.JobLog("完成作业-车型数据采集");
                    }
                    catch (Exception ex)
                    {
                        EventLogs.JobError("作业发生错误-车型数据采集", EventLogs.EVENTID_JOB_ERROR, 0, ex);
                        ExpLog.Write(ex);
                    }
                }
            }
            else
            {
                iscollected = false;
            }
        }
Exemple #32
0
        /// <summary>
        /// Method creates YNC command, sends it to AV unit, and returns response
        /// </summary>
        /// <param name="cmd">YNCCommand.CommandType type</param>
        /// <param name="path">Sequential presentation of YNC function: System,Misc,Network,Network_Name</param>
        /// <returns>XElement response</returns>
        internal XElement SendYNCCommand(MethodType cmd, string path, object value = null)
        {
            string ynccmd = YNCCommand.CreateCommand(cmd, path, value);

            return(Http.Send(Atomics.HostNameOrIPAddress, Atomics.RemoteControlPath, YamahaAVLib.ENums.HttpMethod.Post, ynccmd));
        }
Exemple #33
0
 protected override async Task OnInitializedAsync()
 {
     forecasts = await Http.GetJsonAsync <WeatherForecast[]>("WeatherForecast");
 }
Exemple #34
0
 protected override async Task OnInitAsync()
 {
     currentProfile = await Http.GetJsonAsync <ProfileData>("https://uinames.com/api/?&amount=1&ext");
 }
 public HttpRequestExpectation(Http method, string url, string body = null)
 {
     Method = method;
     Url = url;
     Body = body;
 }
        protected async Task PostCreateSensor()
        {
            await Http.PostAsJsonAsync(baseUrl + "sensors", createSensor);

            await GetSensors();
        }
 public AuthenticateResponse(Http.Response response)
     : base(response)
 {
     LoggedIn = response.Content.Contains("/rs/user/?perform=logout");
 }
        protected async Task DeleteSelectedSensor()
        {
            await Http.DeleteAsync(baseUrl + "sensors/" + selectedId);

            await GetSensors();
        }
 public static async Task <IResult> GetAll(IDictionary <string, object> data)
 {
     return(await Http.Get("/mgr/trans/b2c-details", data));
 }
 protected async Task RefillSensorClick(int id)
 {
     await Http.GetAsync(baseUrl + "refill/" + id);
 }
 public static async Task <IResult> ExecuteInvestBonus(long tbdId, long id)
 {
     return(await Http.Post("/mgr/trans/b2c-details/" + tbdId + "/mer-xfer/" + id + "/execution"));
 }
Exemple #42
0
 public void weather()
 {
     Http myHttp = new Http();
     string weather=myHttp.HttpGet("http://m.weather.com.cn/data/101160201.html", "");
     theContext.Response.Write(weather);
 }
        public static async Task <IResult> SaveInvestBonus(IDictionary <string, object> data)
        {
            var id = data.Take <long>("tbd-id");

            return(await Http.Put("/mgr/trans/b2c-details/" + id + "/mer-xfer", data));
        }
 public ExampleService(List<CartItem> Items, Http _http)
 {
    this.Items = Items;   
 }
 public static async Task <IResult> Delete(long tbdId)
 {
     return(await Http.Delete("/mgr/trans/b2c-details/" + tbdId));
 }
Exemple #46
0
 public SolResponse(Http.Response response)
 {
     this.Roles = GetRoles(response);
     this.UserId = GetUserId(this.Roles);
 }
 /// <summary>
 /// Constructor
 /// </summary>
 public TransferService(string baseUrl, Http http)
     : base(http)
 {
     _baseUrl = baseUrl;
 }
Exemple #48
0
        protected override async Task OnInitializedAsync()
        {
            var res = await Http.GetJsonAsync <List <Good> >("sample-data/goods.json");

            goods = res.Where(i => i.CategoryId == Id).ToList();
        }
        public void ReceiveResponseAsync(Http.Request request)
        {
            if (!IsConnected)
                throw new HttpConnectionException("A network connection is not established.");

            long bytesReceived = 0;
            Tcp.TcpConnection.ProgressDelegate onProgress;
            ResponseBuilder.AsyncCallback callback;

            if (_responseBuilder == null)
                _responseBuilder = new ResponseBuilder(request);


            onProgress = delegate(Tcp.TcpConnection sender, Tcp.DirectionType direction, int packetSize)
            {
                bytesReceived += packetSize;
                Logger.Network.Debug("HttpConnection ID: " + this.GetHashCode().ToString() +
                    "\r\nTcpConnection ID: " + _tcpConnection.GetHashCode().ToString() +
                    "\r\nBytes Received: " + bytesReceived.ToString() +
                    "\r\nResponse Size: " + _responseBuilder.MessageSize.ToString() +
                    "\r\nPacket Size: " + packetSize.ToString() +
                    "\r\nHttpConnection reporting progress receiving from remote host.");
                if (OnProgress != null) OnProgress(this, direction, packetSize, 100, ((decimal)bytesReceived / (decimal)_responseBuilder.MessageSize));
            };

            _tcpConnection.OnProgress += onProgress;
            _tcpConnection.OnError += new Tcp.TcpConnection.ErrorDelegate(ReceiveResponseAsync_OnError);
            _tcpConnection.OnTimeout += new Tcp.TcpConnection.ConnectionDelegate(ReceiveResponseAsync_OnTimeout);

            callback = delegate(MessageBuilder sender, Message.Base message)
            {
                Logger.Network.Debug("HttpConnection ID: " + this.GetHashCode().ToString() + "\r\nTcpConnection ID: " + _tcpConnection.GetHashCode().ToString() + "\r\nHttpConnection receiving data from remote host completed.");
                if (OnComplete != null) OnComplete(this, (Response)message);
            };

            Logger.Network.Debug("HttpConnection ID: " + this.GetHashCode().ToString() + "\r\nTcpConnection ID: " + _tcpConnection.GetHashCode().ToString() + "\r\nHttpConnection beginning receiving of data from remote host.");
            _responseBuilder.ParseAndAttachToBody(_tcpConnection, callback);
        }
        private async Task UpdatePaciente()
        {
            await Http.PutAsJsonAsync <Paciente>($"api/Pacientes/{id}", newPaciente);

            NavigationManager.NavigateTo("Pacientes");
        }
 public ResponseBuilder(Http.Request request)
 {
     Request = request;
     AllHeadersReceived = false;
     MessageSize = -1;
 }
Exemple #52
0
        static void Worker(string combo)
        {
            try
            {
                Variables.proxyIndex = Variables.proxyIndex >= Variables.proxies.Length ? 0 : Variables.proxyIndex;
                var proxy       = Variables.proxies[Variables.proxyIndex];
                var credentials = combo.Split(new char[] { ':', ';', '|' }, StringSplitOptions.RemoveEmptyEntries);
                using (var req = new HttpRequest()
                {
                    KeepAlive = true,
                    IgnoreProtocolErrors = true,
                    Proxy = ProxyClient.Parse(proxyType, proxy)
                })
                {
                    req.Proxy.ConnectTimeout            = proxyTimeout;
                    req.SslCertificateValidatorCallback = (RemoteCertificateValidationCallback)Delegate.Combine(req.SslCertificateValidatorCallback,
                                                                                                                new RemoteCertificateValidationCallback((object obj, X509Certificate cert, X509Chain ssl, SslPolicyErrors error) => (cert as X509Certificate2).Verify()));


                    var U_A            = Http.RandomUserAgent();
                    var Epic_Device    = Guid.NewGuid().ToString();
                    var EPIC_FUNNEL_ID = Functions.Resolve("?h?h?h?h?h?h?h?h?h?h?h?h?h?h?h?h?h?h?h?h?h?h?h?h?h?h?h?h?h?h?h?h");
                    req.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko");
                    req.AddHeader("Pragma", "no-cache");
                    req.AddHeader("Accept", "*/*");
                    var    res7       = req.Get("https://www.epicgames.com/id/api/csrf");
                    string text7      = res7.ToString();
                    var    XSRF_TOKEN = req.Cookies.GetCookies("https://www.epicgames.com/id/api/csrf")["XSRF-TOKEN"].Value;

                    req.ClearAllHeaders();
                    req.AllowAutoRedirect = false;

                    req.AddHeader("EPIC_DEVICE", Epic_Device);
                    req.AddHeader("EPIC_FUNNEL_ID", EPIC_FUNNEL_ID);
                    req.AddHeader("XSRF-TOKEN", XSRF_TOKEN);
                    req.AddHeader("User-Agent", U_A);
                    req.AddHeader("Pragma", "no-cache");
                    req.AddHeader("Accept", "*/*");
                    req.AddHeader("Host", "accounts.launcher-website-prod07.ol.epicgames.com");
                    req.AddHeader("Accept-Language", "nb-NO,nb;q=0.9,no-NO;q=0.8,no;q=0.6,nn-NO;q=0.5,nn;q=0.4,en-US;q=0.3,en;q=0.1");
                    req.AddHeader("Accept-Encoding", "gzip, deflate, br");
                    req.AddHeader("X-XSRF-TOKEN", XSRF_TOKEN);
                    req.AddHeader("Origin", "https://accounts.launcher-website-prod07.ol.epicgames.com");
                    req.AddHeader("DNT", "1");
                    req.AddHeader("Connection", "keep-alive");
                    req.AddHeader("Referer", "https://accounts.launcher-website-prod07.ol.epicgames.com/launcher/addFriends");

                    var    res0  = req.Post("https://accounts.launcher-website-prod07.ol.epicgames.com/launcher/sendFriendRequest", "inputEmail=" + credentials[0] + "&tab=connections", "application/x-www-form-urlencoded");
                    string text0 = res0.ToString();

                    if (text0.Contains("class=\"fieldValidationError\"><label for=\"inputEmail\" class=\"fieldValidationError\">Sorry, it appears that you have tried to submit the form twice. Please click only once.</label></div>") || text0.Contains("class=\"fieldValidationError\"><label for=\"inputEmail\" class=\"fieldValidationError\">Sorry, you are visiting our service too frequent, please try again later.</label></div>"))
                    {
                        Variables.combos.Enqueue(combo);
                        Variables.proxyIndex++;
                        Variables.Errors++;
                    }
                    else if (text0.Contains("class=\"fieldValidationError\"><label for=\"inputEmail\" class=\"fieldValidationError\">Please Sign In</label></div>"))
                    {
                        Variables.Valid++;
                        Variables.Checked++;
                        Variables.cps++;
                        lock (Variables.WriteLock)
                        {
                            Variables.remove(combo);
                            if (Config.kekr_UI == "LOG")
                            {
                                Console.WriteLine($"[+] {combo}", Color.Green);
                            }
                            File.AppendAllText(Variables.results + "Registered.txt", combo + Environment.NewLine);
                        }
                    }
                    else if (text0.Contains("class=\"fieldValidationError\"><label for=\"inputEmail\" class=\"fieldValidationError\">Sorry, this account was not found</label></div>"))
                    {
                        Variables.Invalid++;
                        Variables.Checked++;
                        Variables.cps++;
                        lock (Variables.WriteLock)
                        {
                            Variables.remove(combo);
                            File.AppendAllText(Variables.results + "Not Registered.txt", combo + Environment.NewLine);
                        }
                    }
                    else
                    {
                        Variables.combos.Enqueue(combo);
                        Variables.proxyIndex++;
                        Variables.Errors++;
                    }
                }
            }
            catch
            {
                Variables.combos.Enqueue(combo);
                Variables.proxyIndex++;
                Variables.Errors++;
            }
        }
        /// <summary>
        /// Constructor
        /// </summary>
        public WebhookService(Http http) : base(http)
        {

        }
Exemple #54
0
        protected override async Task OnInitializedAsync()
        {
            var forecasts = await Http.GetFromJsonAsync <WeatherForecast[]>("sample-data/weather.json");

            Forecast = forecasts.Single(forecast => forecast.Date.ToString("yyy-MM-dd").Equals(Date));
        }
Exemple #55
0
 //private bool isRunning = false;
 void Start()
 {
     _instance = this;
 }
        public async Task UsesVersion(HttpProtocols protocols, bool tls, bool allowUnencryptedHttp2, string specified, string expectedVersion, string expectedResponse, bool failure = false)
        {
            // wheeee, macOS doesn't support ALPN so it can't do HTTP/2 over TLS
            // it also misbehaves when requesting HTTP/2 over non-TLS
            // so let's skip all those tests on macOS.
            Skip.If(
                RuntimeInformation.IsOSPlatform(OSPlatform.OSX) && tls && (protocols == HttpProtocols.Http2 || protocols == HttpProtocols.Http1AndHttp2) && specified == "2.0",
                "HTTP/2 over TLS is not currently supported on MacOS"
                );

            bool oldMode = HttpSettings.GlobalAllowUnencryptedHttp2;

            try
            {
                HttpSettings.GlobalAllowUnencryptedHttp2 = allowUnencryptedHttp2;

                var uri = _server.GetUri(protocols, tls);
                Log($"Server is on {uri}; specifying: '{specified}'");
                var request = Http.Request(uri, new HttpSettings {
                    ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
                });
                if (specified is object)
                {
                    request = request.WithProtocolVersion(new Version(specified));
                }
                HttpCallResponse <string> result;
                try
                {
                    result = await request.ExpectString().GetAsync();
                }
                catch (Exception ex)
                {
                    if (failure)
                    {
                        Log(ex.ToString());
                        return;
                    }
                    else
                    {
                        throw;
                    }
                }

                Log($"As sent: {result?.RawRequest?.Version}, received: {result?.RawResponse?.Version}");

                if (failure)
                {
                    Assert.NotNull(result.Error);
                    Log(result.Error.ToString());
                }
                else
                {
                    Assert.Null(result.Error);
                    Assert.Equal(expectedVersion, result.RawResponse?.Version?.ToString());
                    Assert.Equal(expectedResponse, result.Data);
                }
            }
            finally
            {
                HttpSettings.GlobalAllowUnencryptedHttp2 = oldMode;
            }
        }
 /// <summary>
 /// Constructor
 /// </summary>
 public OrderService(string baseUrl, Http http) : base(http)
 {
     _baseUrl = baseUrl;
 }
        protected async override void OnInitialized()
        {
            var bytes = await Http.GetByteArrayAsync("/Assembly-CSharp.dll");

            System.Reflection.Assembly.Load(bytes);
        }
 public AuthService(Http http) : base(http) { }
 protected override async Task OnInitializedAsync()
 {
     newPaciente = await Http.GetFromJsonAsync <Paciente>($"api/Pacientes/{id}");
 }