Inheritance: MonoBehaviour
示例#1
0
        public async Task <string> SignInHandle()
        {
            using (var reader = new StreamReader(HttpContext.Request.Body))
            {
                var body = reader.ReadToEnd();

                // Do something
                var p = ParseJson.parseSimpleParam(body);

                List <string> key = new List <string>(), val = new List <string>();
                key.Add("account");
                val.Add(p["account"]);
                key.Add("password");
                val.Add(p["password"]);
                //HttpContext.Response.Cookies =;
                if (DataBaseAccess.exist(typeof(Account), key, val))
                {
                    await testAsync(p["account"], p["password"]);

                    return("SignIn Successful!");
                }
                else
                {
                    return("SignIn failed!");
                }
            }
        }
示例#2
0
        public static async Task StartDev(TelegramBotClient client, Telegram.Bot.Types.Message message, string baseAdress, string port)
        {
            using (var host = new HttpClient())
            {
                ClientExtension.PrepareHeaderForJenkins(host);
                var lastBuild = await ParseJson.ResponseJson <JenkisBuildJson>(host, $"http://{baseAdress}:{port}/job/first/lastBuild/api/json");

                var result = await host.GetAsync($"http://{baseAdress}:{port}/job/first/build?token=someAuthorizationFuckingTocketThatICantFindWhereToGenerate");

                JenkisBuildJson resId;
                do
                {
                    Thread.Sleep(1000);
                    resId = await ParseJson.ResponseJson <JenkisBuildJson>(host, $"http://{baseAdress}:{port}/job/first/lastBuild/api/json");
                } while (lastBuild.number == resId.number);
                if (resId.result != null && resId.result.Equals("SUCCESS"))
                {
                    await client.SendTextMessageAsync(message.Chat.Id, $"Готово, билд{resId.displayName}");
                }
                else
                {
                    await client.SendTextMessageAsync(message.Chat.Id, $"Что то пошло не так:(, билд{resId.displayName}");
                }
            }
        }
            public async Task PopulatesDocumentAndKey()
            {
                // Given
                TestDocument document = new TestDocument(_jsonContent);
                ParseJson    json     = new ParseJson("Foo", true);

                // When
                ImmutableArray <TestDocument> results = await ExecuteAsync(document, json);

                // Then
                TestDocument result = results.ShouldHaveSingleItem();

                result.Count.ShouldBe(9); // Includes property metadata
                result["Email"].ShouldBe("*****@*****.**");
                result["Active"].ShouldBe(true);
                result["CreatedDate"].ShouldBe("2013-01-20T00:00:00Z");
                result["Roles"].ShouldBe(new object[] { "User", "Admin", 11 });
                IMetadata nestedObject = result.GetMetadata("Description");

                nestedObject.ShouldNotBeNull();
                nestedObject["Height"].ShouldBe(5);
                IMetadata metadata = result.GetMetadata("Foo");

                metadata.ShouldNotBeNull();
                metadata["Email"].ShouldBe("*****@*****.**");
                metadata["Active"].ShouldBe(true);
                metadata["CreatedDate"].ShouldBe("2013-01-20T00:00:00Z");
                metadata["Roles"].ShouldBe(new object[] { "User", "Admin", 11 });
                nestedObject = metadata.GetMetadata("Description");
                nestedObject.ShouldNotBeNull();
                nestedObject["Height"].ShouldBe(5);
            }
示例#4
0
        public string SignUpHandle(string ID, string password)
        {
            using (var reader = new StreamReader(HttpContext.Request.Body))
            {
                var body = reader.ReadToEnd();

                // Do something
                var p = ParseJson.parseSimpleParam(body);

                string  id = getID();
                Account a  = new Account(p["account"], id, p["password"], DateTime.Now, DateTime.Now, p["IP"]);
                User    u  = new User(id, null, null, normal, null);
                //people tem = new people(p["ID"], p["password"]);


                if (DataBaseAccess.insertObj(a) && DataBaseAccess.insertObj(u))
                {
                    return("SignUp Successful!");
                }
                else
                {
                    return("SignUp failed!");
                }
            }
        }
示例#5
0
        public string UpdateHandle()
        {
            using (var reader = new StreamReader(HttpContext.Request.Body))


            {
                //var a = ConnectionFactory.CreateConnection(@"Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME = orcl)));User Id=system;Password=990503");
                //a.Open();
                //OracleHelper.ExecuteSql(a, @"update DBUser set  userName ='******' , userGender ='0'  , userLevel = 1 , userIconID ='123124'  where  userID = '9770a066-cc46-4'");

                var body = reader.ReadToEnd();

                // Do something
                var           p = ParseJson.parseSimpleParam(body);
                List <string> key = new List <string>(), val = new List <string>();
                User          u = new User(p["ID"], p["name"], p["gender"], 1, null);
                //HttpContext.Response.Cookies =;
                if (DataBaseAccess.updateObj(u))
                {
                    return("update Successful!");
                }
                else
                {
                    return("update failed!");
                }

                //return View();*/
            }
        }
示例#6
0
    static void Main(string[] args)
    {
        ParseJson   pjs   = new ParseJson();
        GetJson     gjson = pjs.Serializer();
        ConfigModel cf    = gjson.RetrieveValues();
        //cf.Username and other members

        //OR you can have:  ConfigModel cf = pjs.Serializer().RetrieveValues();
    }
示例#7
0
        static void Main(string[] args)
        {
            ParseJson List = new ParseJson("Data/generatedData.json");

            Console.WriteLine("There are " + List.getFemaleCount() + " women and " + List.getMaleCount() + " men in this data");
            Console.WriteLine("The average age is: " + List.getAverageAge());

            Console.ReadKey();
        }
示例#8
0
        public void updateStreamList( )
        {
            CookieAwareWebClient cwc = new CookieAwareWebClient();

            System.IO.Stream stream = cwc.downloadURL(channelsUrl);
            if (stream != null)
            {
                channelList = ParseJson <Channels> .ReadObject(stream);
            }
        }
示例#9
0
 /// <summary>
 /// Initializes the library with extended parameters.
 /// </summary>
 /// <param name="appId">Unique VK app identifier. Get it at vk.com/dev -> App Settings</param>
 /// <param name="appSecret">App secret key. Used only with secure section methods and with direct auth.</param>
 /// <param name="apiVersion">API version the library is going to use. Min: 5.63</param>
 /// <param name="requestMethod">GET or POST requests the library should use?</param>
 /// <param name="parseJson">Should the library log received JSONs or focus on performance?</param>
 /// <param name="logger">Logger the library should use. By default is logs info into DEBUG output.</param>
 public Vkontakte(int appId, ILogger logger, string appSecret = "", string apiVersion  = "5.63",
                  RequestMethod requestMethod = RequestMethod.Get, ParseJson parseJson = ParseJson.FromString)
 {
     AppId          = appId;
     Logger         = logger;
     AppSecret      = appSecret;
     ApiVersion     = apiVersion;
     HttpService    = new DefaultHttpService(logger);
     _requestMethod = requestMethod;
     _parseJson     = parseJson;
 }
示例#10
0
        public void updateChat(UInt32 id)
        {
            CookieAwareWebClient cwc = new CookieAwareWebClient();

            System.IO.Stream stream = cwc.downloadURL(String.Format(messagesUrl, id));

            if (stream != null)
            {
                chat = ParseJson <ChatMessages> .ReadObject(stream);
            }
        }
 /// <summary>
 /// Initializes the library with extended parameters.
 /// </summary>
 /// <param name="appId">Unique VK app identifier. Get it at vk.com/dev -> App Settings</param>
 /// <param name="appSecret">App secret key. Used only with secure section methods and with direct auth.</param>
 /// <param name="apiVersion">API version the library is going to use. Min: 5.63</param>
 /// <param name="requestMethod">GET or POST requests the library should use?</param>
 /// <param name="parseJson">Should the library log received JSONs or focus on performance?</param>
 /// <param name="httpService">
 /// HttpService the library should use. You can inject your own implementation of IHttpService
 /// into the library if default one does not suite you for some reasons.
 /// </param>
 public Vkontakte(int appId, string appSecret, IHttpService httpService,
                  string apiVersion   = "5.63", RequestMethod requestMethod = RequestMethod.Get,
                  ParseJson parseJson = ParseJson.FromString)
 {
     AppId          = appId;
     AppSecret      = appSecret;
     ApiVersion     = apiVersion;
     HttpService    = httpService;
     Logger         = new DefaultLogger();
     _requestMethod = requestMethod;
     _parseJson     = parseJson;
 }
示例#12
0
            public async Task ReturnsDocumentOnError()
            {
                // Given
                TestDocument         document = new TestDocument("asdf");
                ParseJson            json     = new ParseJson("MyJson");
                TestExecutionContext context  = new TestExecutionContext(document);

                context.TestLoggerProvider.ThrowLogLevel = LogLevel.None;

                // When
                TestDocument result = await ExecuteAsync(context, json).SingleAsync();

                // Then
                result.ShouldBe(document);
            }
示例#13
0
 // Find elements that have given XPath, and return this list
 public ReadOnlyCollection <IWebElement> FindElements(string xPathElement, string xPathSite = "NoWebSite")
 {
     if (xPathSite != "NoWebSite")
     {
         xPathElement = ParseJson.FindXpath(xPathSite, xPathElement);
     }
     try
     {
         Elements = driverChrome.FindElements(By.XPath(xPathElement));
         return(Elements);
     }
     catch (Exception)
     {
         return(null);
     }
 }
示例#14
0
            public async Task FlattensTopLevel()
            {
                // Given
                TestDocument document = new TestDocument(_jsonContent);
                ParseJson    json     = new ParseJson();

                // When
                TestDocument result = await ExecuteAsync(document, json).SingleAsync();

                // Then
                result.Count.ShouldBe(8); // Includes property metadata
                ((string)result["Email"]).ShouldBe("*****@*****.**");
                ((bool)result["Active"]).ShouldBeTrue();
                ((DateTime)result["CreatedDate"]).ShouldBe(new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc));
                ((IEnumerable)result["Roles"]).ShouldBe(new[] { "User", "Admin" });
            }
示例#15
0
 // Fill box in browser
 public bool FillElement(string xPathElement, string elementName, string xPathSite = "NoWebSite")
 {
     if (xPathSite != "NoWebSite")
     {
         xPathElement = ParseJson.FindXpath(xPathSite, xPathElement);
     }
     try
     {
         Element = driverChrome.FindElement(By.XPath(xPathElement));
         Element.SendKeys(elementName);
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
示例#16
0
            public async Task GeneratesDynamicObject()
            {
                // Given
                TestDocument document = new TestDocument(_jsonContent);
                ParseJson    json     = new ParseJson("MyJson");

                // When
                TestDocument result = await ExecuteAsync(document, json).SingleAsync();

                // Then
                result.Count.ShouldBe(5); // Includes property metadata
                result["MyJson"].ShouldBeOfType <ExpandoObject>();
                ((string)((dynamic)result["MyJson"]).Email).ShouldBe("*****@*****.**");
                ((bool)((dynamic)result["MyJson"]).Active).ShouldBeTrue();
                ((DateTime)((dynamic)result["MyJson"]).CreatedDate).ShouldBe(new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc));
                ((IEnumerable)((dynamic)result["MyJson"]).Roles).ShouldBe(new[] { "User", "Admin" });
            }
示例#17
0
        public string UpdateReciverHandle()
        {
            using (var reader = new StreamReader(HttpContext.Request.Body))
            {
                var body = reader.ReadToEnd();

                // Do something
                var p = ParseJson.parseSimpleParam(body);

                UserInformation u = new UserInformation(p["rID"], p["ID"], p["name"], p["province"], p["city"], p["district"], p["street"], p["detailAdress"], p["phone"]);
                if (DataBaseAccess.updateObj(u))
                {
                    return("DelReciver Successful!");
                }
                else
                {
                    return("DelReciver failed!");
                }

                //return View();*/
            }
        }
示例#18
0
        public string UpdateItemHandle()
        {
            using (var reader = new StreamReader(HttpContext.Request.Body))
            {
                var body = reader.ReadToEnd();

                // Do something
                var p = ParseJson.parseSimpleParam(body);

                Item u = new Item(p["i_ID"], p["s_ID"], p["name"], double.Parse(p["price"]), null, p["introduction"], int.Parse(p["followNum"]), double.Parse(p["score"]));
                if (DataBaseAccess.updateObj(u))
                {
                    return("UpdateItem Successful!");
                }
                else
                {
                    return("UpdateItem failed!");
                }

                //return View();*/
            }
        }
示例#19
0
        // Check the element is available or not
        public bool CheckElementAvailable(string xPathElement, int choose, string xPathSite = "NoWebSite")
        {
            if (xPathSite != "NoWebSite")
            {
                xPathElement = ParseJson.FindXpath(xPathSite, xPathElement);
            }
            try
            {
                if (choose == -1)
                {
                    Element = waitZ.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(By.XPath(xPathElement)));
                }
                else if (choose == 0)
                {
                    Element = waitS.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(By.XPath(xPathElement)));
                }
                else if (choose == 1)
                {
                    Element = waitM.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(By.XPath(xPathElement)));
                }
                else if (choose == 2)
                {
                    Element = waitB.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(By.XPath(xPathElement)));
                }
            }
            catch (Exception)
            {
                return(false);
            }

            if (Element == null)
            {
                return(false);
            }

            return(true);
        }
示例#20
0
        public async Task <string> SignOutHandleAsync()
        {
            using (var reader = new StreamReader(HttpContext.Request.Body))
            {
                var body = reader.ReadToEnd();

                // Do something
                var p = ParseJson.parseSimpleParam(body);

                List <string> key = new List <string>(), val = new List <string>();

                //HttpContext.Response.Cookies =;
                if (DataBaseAccess.exist(typeof(Account), key, val))
                {
                    await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

                    return("SignOut Successful!");
                }
                else
                {
                    return("SignOut failed!");
                }
            }
        }
示例#21
0
        private async Task <int> AddLineInfo(string departCity, string arriveCity, string port, string lineTitle, string days, string scenic, string hotels, string supplier, string pmRecommendation, string url, int soldqty, int commentNumber, string lineNo, string cityCode)
        {
            Guid     lineguid = Guid.NewGuid();
            DateTime date     = DateTime.Now;

            _dbContext.T_Line.Add(new Line()
            {
                Id               = lineguid,
                SiteName         = "途牛",
                TypeName         = "自助游",
                Departcity       = departCity,
                ArriveCity       = arriveCity,
                Port             = port,
                Linetitle        = lineTitle,
                Days             = days,
                Scenic           = scenic,
                Hotels           = hotels,
                Supplier         = supplier,
                Traffic          = String.Empty,
                Trafficdetail    = String.Empty,
                Soldqty          = soldqty,
                Url              = url,
                Reco             = string.Empty,
                CreateDate       = date,
                CommentNumber    = commentNumber,
                PmRecommendation = pmRecommendation
            });
            //if (num <= 0) return num;

            #region 抓取价格日历json

            var webclient = new WebClient {
                Encoding = System.Text.Encoding.UTF8
            };
            //定义以UTF-8格式接收文本信息,规避WebClient接收文本信息时夹带乱码问题
            urlPrice = $"http://www.tuniu.com//package/api/calendar?productId={lineNo}&bookCityCode={cityCode}";
            var htmlPrice = webclient.DownloadString(urlPrice);


            ParseJson jobInfoList = JsonConvert.DeserializeObject <ParseJson>(htmlPrice);

            if (jobInfoList == null || jobInfoList.Success != true || jobInfoList.Data?.CalendarInfo == null)
            {
                return(-1);
            }


            foreach (var t in jobInfoList.Data.CalendarInfo)
            {
                adultPrice = t.AdultPrice;
                childPrice = t.ChildPrice;
                Groupdate  = t.PlanDate;
                if (!string.IsNullOrEmpty(Groupdate))
                {
                    Guid groupPriceGuid = Guid.NewGuid();
                    _dbContext.T_GroupPrice.Add(new GroupPrice()
                    {
                        Id         = groupPriceGuid,
                        Lineid     = lineguid,
                        GroupDate  = Groupdate,
                        AdultPrice = adultPrice,
                        ChildPrice = childPrice
                    });

                    //dbContext.Entry<GroupPrice>(new GroupPrice()
                    //{
                    //    Id = groupPriceGuid,
                    //    Lineid = lineguid,
                    //    GroupDate = Groupdate,
                    //    AdultPrice = adultPrice,
                    //    ChildPrice = childPrice


                    //}).State = EntityState.Added;
                }
            }
            return(await _dbContext.SaveChangesAsync());



            #endregion
        }
示例#22
0
        public ActionResult PostPolymericList()
        {
            string subject   = DoRequest.GetFormString("subject").Trim();
            string excelPath = DoRequest.GetFormString("excel").Trim();

            string   sdate     = DoRequest.GetFormString("sdate").Trim();
            int      shours    = DoRequest.GetFormInt("shours");
            int      sminutes  = DoRequest.GetFormInt("sminutes");
            DateTime startDate = Utils.IsDateString(sdate) ? DateTime.Parse(sdate + " " + shours + ":" + sminutes + ":00") : DateTime.Now;

            string   edate    = DoRequest.GetFormString("edate").Trim();
            int      ehours   = DoRequest.GetFormInt("ehours");
            int      eminutes = DoRequest.GetFormInt("eminutes");
            DateTime endDate  = Utils.IsDateString(edate) ? DateTime.Parse(edate + " " + ehours + ":" + eminutes + ":59") : DateTime.Now.AddDays(7);

            string summary = DoRequest.GetFormString("summary").Trim();

            if (subject.Length < 1)
            {
                return(Json(new { error = true, message = "请填写主题..." }));
            }
            if (subject.Length > 50)
            {
                return(Json(new { error = true, message = "主题不能超过50个字符..." }));
            }
            if (summary.Length > 500)
            {
                return(Json(new { error = true, message = "摘要不能超过500个字符..." }));
            }

            Robots _rbt = new Robots();

            System.Text.StringBuilder url = new System.Text.StringBuilder();
            url.Append(base._config.UrlHome + "Tools/ImportFromExcel?");
            url.Append(Cookies.CreateVerifyString());

            System.Text.StringBuilder postData = new System.Text.StringBuilder();
            postData.Append("subject=" + DoRequest.UrlEncode(AES.Encode(subject)));
            postData.Append("&excel=" + DoRequest.UrlEncode(AES.Encode(excelPath)));
            postData.Append("&sdate=" + startDate.ToString("yyyy-MM-dd HH:mm:ss"));
            postData.Append("&edate=" + endDate.ToString("yyyy-MM-dd HH:mm:ss"));
            postData.Append("&summary=" + DoRequest.UrlEncode(AES.Encode(summary)));

            string html = _rbt.Post(url.ToString(), postData.ToString(), "utf-8");

            if (_rbt.IsError)
            {
                return(Json(new { error = true, message = _rbt.ErrorMsg }));
            }
            if (string.IsNullOrEmpty(html))
            {
                return(Json(new { error = true, message = "远程页面无响应..." }));
            }

            ParseJson pJson = new ParseJson();
            SortedDictionary <string, string> list = pJson.Parse(html);
            bool isError = false;

            if (pJson.GetJsonValue(list, "error") == "true")
            {
                isError = true;
            }
            return(Json(new { error = isError, message = pJson.GetJsonValue(list, "message") }));
        }