Esempio n. 1
0
        public String getTempAuthorizeCode()
        {
            string    returnMsg = string.Empty;
            WebClient webClient = WebClient.instance;
            String    param     = Consts.CHECK_USER + getParams(mModel);

            try
            {
                if (mModel != null)
                {
                    String userInfo = webClient.Post(param, "", "");
                    return(getAuthorizeCode(userInfo));
                }
                return(null);
            }
            catch (Exception ex)
            {
                if (currentTryRunNum == TRY_AGAIN_MUN)
                {
                    FailRequestManager.mInstance.saveInFailList(mModel.UserID, Convert.ToDateTime(mSyncDay), param, (ex == null ? "" : ex.Message));
                    return(null);
                }
                else
                {
                    currentTryRunNum++;
                    return(getTempAuthorizeCode());
                }
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Initiates a call to the destination phone number from the local phone
        /// </summary>
        public bool Call(string localPhone, string destinationPhoneNumber)
        {
            try
            {
                VariableCollection parameters = GenerateParameters();

                parameters["outgoingNumber"].Value   = destinationPhoneNumber;
                parameters["forwardingNumber"].Value = localPhone;
                parameters["subscriberNumber"].Value = "undefined";
                parameters["phoneType"].Value        = 2;
                parameters["remember"].Value         = 0;
                parameters["_rnr_se"].Value          = Session;

                var result = WebClient.Post(GenerateUrl(), parameters);

                GetFolderResult returnValue = new GetFolderResult();
                var             dictionary  = result.Content.ToObject <Dictionary <string, object> >();

                return(Convert.ToBoolean(dictionary["ok"]));
            }
            catch (Exception ex)
            {
                throw new CallException(ex);
            }
        }
Esempio n. 3
0
        /// <summary>
        /// 检查网站激活状态
        /// </summary>
        internal static void CheckActiveState()
        {
            object checkCache = Cms.Cache.Get(checkKey);

            if (checkCache == null)
            {
                try
                {
                    //如果Key为空则Key为temp.ops.cc产生的Key
                    string key = Settings.License_KEY
                                 ?? "YmIyNDAwMGI3YmEyZGMwZTgxZWI2OGQxYzk3MWU4NWI=";

                    WebClient client       = new WebClient("http://ct.ops.cc/ct/license");
                    string    responseText = client.Post(
                        "token=YmIyNDAwMGI3YmEyZGMwZTgxZWI2OGQxYzk3MWU4NWI&license_key="
                        + key + "&license_name=" + Settings.License_NAME);

                    activeInfo = responseText;
                }
                catch
                {
                    //如果校验服务器请求产生问题,则不检测激活状态
                    //activeInfo = null;
                    //activeInfo = ex.Message;
                }
            }
        }
Esempio n. 4
0
        private SportData getSportDataExt(string param2)
        {
            string param = Consts.GET_SPORT_DATA + getParams();

            try
            {
                String    sleepInfo = webClient.Post(param, param2, CONTENT_TYPE);
                SportData sportData = JsonConvert.DeserializeObject <SportData>(sleepInfo);
                if (sportData == null || sportData.sport == null)
                {
                    sportData = new SportData();
                    Sport sport = new Sport();
                    sportData.sport = sport;
                }
                return(sportData);
            }
            catch (Exception ex)
            {
                if (currentTryRunNum == TRY_AGAIN_MUN)
                {
                    FailRequestManager.mInstance.saveInFailList(mUserModel.UserID, Convert.ToDateTime(mSyncDay), param, (ex == null ? "" : ex.Message));
                    return(null);
                }
                else
                {
                    currentTryRunNum++;
                    return(getSportDataExt(param2));
                }
            }
        }
Esempio n. 5
0
        private HeartrateData getHeartrateDataExt(string param2)
        {
            string param = Consts.GET_HEART_DATA + getParams();

            try
            {
                String        sleepInfo = webClient.Post(param, param2, CONTENT_TYPE);
                HeartrateData data      = JsonConvert.DeserializeObject <HeartrateData>(sleepInfo);
                if (data == null || data.heartrate == null)
                {
                    data = new HeartrateData();
                    Heartrate heartrate = new Heartrate();
                    data.heartrate = heartrate;
                }
                return(data);
            }
            catch (Exception ex)
            {
                if (currentTryRunNum == TRY_AGAIN_MUN)
                {
                    FailRequestManager.mInstance.saveInFailList(mUserModel.UserID, Convert.ToDateTime(mSyncDay), param, (ex == null ? "" : ex.Message));
                    return(null);
                }
                else
                {
                    currentTryRunNum++;
                    return(getHeartrateDataExt(param2));
                }
            }
        }
 public AmqpServerInfo RegisterQueue(AmqpRegistrationParams parameters)
 {
     using (WebClient webClient = new WebClient().SetHeaders(_credentials, _url))
     {
         return(webClient.Post <AmqpServerInfo>(ItemSenseEndpoints.MessageQueue, parameters));
     }
 }
Esempio n. 7
0
 /// <summary>
 /// Posts the specified data to this url and returns the response as string.
 /// All items in the postData object will be sent as individual FORM parameters to the destination.
 /// </summary>
 public static async Task <string> Post(this Uri url, Dictionary <string, string> postData, Action <WebClient> customiseClient = null)
 {
     using (var client = new WebClient())
     {
         customiseClient?.Invoke(client);
         return(await client.Post(url.ToString(), postData));
     }
 }
Esempio n. 8
0
        private async Task <Clothes[]> GetResults(ClothesQuery query)
        {
            string      content  = BuildSearchRequestBody(query);
            WebResponse response = await _webClient.Post(_baseUrl, content);

            CheckIfReponseIsSuccessful(response);

            return(await _searchResultsParser.Parse(response.Content));
        }
        protected string submitQueries(string json)
        {
            var query = FILTER_STR_HEADER + "*";
            var path  = GenerateGetPath(HttpMethods.GET, query);

            UseCompression = true;
            json           = WebClient.Post(path, json).ToString();
            return(json);
        }
Esempio n. 10
0
        public async Task <UrlResponseResult> Publish(string objectId)
        {
            long dt = Celia.io.Core.MicroServices.Utilities.DateTimeUtils
                      .GetCurrentMillisecondsTimestamp();
            string appsecret = this._appSecret;
            string path      = "/api/images/publish";

            string sign = HashUtils.OpenApiSign(this._appId,
                                                this._appSecret, dt, path);
            //{appsecret}!@{appid}#{timestamp}&{content}

            var res = await _client.Post(
                $"{_hostAndPort.ToString().Trim(new char[] { })}/api/images/publish")
                      .Header("appId", this._appId).Header("ts", dt).Header("sign", sign)
                      .JsonData <MediaElementActionRequest>(new MediaElementActionRequest()
            {
                ObjectId = objectId
            })
                      .ResultAsync();

            var obj = JObject.Parse(res).ToObject(typeof(UrlResponseResult));

            return(obj as UrlResponseResult);
        }
Esempio n. 11
0
        public void TestDeserialize()
        {
            var data = new MyPostData {
                Int = 1, Str = "Lorem Ipsum"
            };

            using (var client = new WebClient()) {
                var postContent      = WebRequest.JsonContent(data);
                var postHttpResponse = client.Post(_url, postContent);
                var postData         = postHttpResponse.Deserialize <MyPostData>();

                Assert.IsNotNull(postData);
                Assert.AreEqual(data.Int, postData.Int);
                Assert.AreEqual(data.Str, postData.Str);
            }
        }
Esempio n. 12
0
        public SaleQueueResponse SubmitSaleXML(string xmlString)
        {
            var query      = FILTER_STR_HEADER;
            var path       = GenerateGetPath(HttpMethods.POST, query);
            var strContent = xmlString;

            //var postRequest = new PostRequest()
            //{
            //    filter = query,
            //    updatetype = PostUpdateType.INSERT.ToString(),
            //    updateObject = strContent
            //};
            //strContent = JsonConvert.SerializeObject(postRequest);
            WebClient.ReturnType = BreezeReturnType.xml;
            var ret = WebClient.Post(path, strContent).ToString();

            return(DeserialXML <SaleQueueResponse>(ret));
        }
Esempio n. 13
0
        /// <summary>
        /// Executes the secondary process of POSTing login credentials
        /// </summary>
        /// <param name="emailAddress"></param>
        /// <param name="password"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        protected virtual LoginResult ExecuteLogin(string emailAddress, string password, VariableCollection parameters)
        {
            try
            {
                parameters["Email"].Value  = emailAddress;
                parameters["Passwd"].Value = password;

                Result result = WebClient.Post(GenerateUrl(), parameters);
                Session = result.GetInputValueByRegExLiberal("_rnr_se");

                string genericInformationPart1 = result.GetBlock("_gcData =", "'contacts'");
                string genericInformationPart2 = "'rank':" + result.GetBlock("'rank':", "};") + "}";

                Account = (genericInformationPart1 + genericInformationPart2).ToObject <AccountData>();

                Account.contacts = new Dictionary <string, Contact>();
                var contactDetails = result.GetBlocks("{\"contactId\":", true, "{\"contactId\":", "'rank':");
                if (contactDetails != null)
                {
                    foreach (var contactDetail in contactDetails)
                    {
                        string  json    = contactDetail.Substring(0, contactDetail.LastIndexOf('}') + 1);
                        Contact contact = json.ToObject <Contact>();
                        if (!Account.contacts.ContainsKey(contact.contactId) || Account.contacts[contact.contactId].phoneNumber == null)
                        {
                            Account.contacts[contact.contactId] = contact;
                        }
                    }
                }

                LoginResult returnValue = new LoginResult();
                CheckRelogin(returnValue, result);

                if (!returnValue.RequiresRelogin)
                {
                    LoginParameters = parameters;
                }
                return(returnValue);
            }
            catch (Exception ex)
            {
                throw new LoginException(ex);
            }
        }
Esempio n. 14
0
 public ActionResult Token([FromBody] IDictionary <string, string> parameters)
 {
     try
     {
         WebClient webClient    = new WebClient();
         string    baseUrl      = Configuration["AppSettings:IdsUrl"];
         string    result       = webClient.Post(baseUrl + "connect/token").Data(parameters).Result();
         var       returnResult = JsonConvert.DeserializeObject <TokenReturn>(result);
         if (string.IsNullOrEmpty(returnResult.access_token))
         {
             return(Fail(result));
         }
         return(Success("操作成功", result));
     }
     catch (Exception ex)
     {
         return(Fail(ex.Message));
     }
 }
Esempio n. 15
0
        /// <summary>
        /// Retrieves the Inbox folder
        /// </summary>
        /// <param name="pageNumber">Page number to retrieve</param>
        /// <param name="urlOverride">URL override, if retrieving from a different location</param>
        /// <param name="rnr_se">URL override, if retrieving from a different location</param>
        ///
        public HtmlNodeCollection InboxMessages(string rnr_se, uint?pageNumber = null, string urlOverride = null)
        {
            string base_url = (urlOverride ?? GenerateUrl());
            string get_url  = base_url;

            VariableCollection parameters = GenerateParameters(pageNumber);

            try {
                var result = WebClient.Get(get_url, parameters);
                //TODO if no messages
                GetFolderResult messageJson = new GetFolderResult();
                string          json        = result.GetJsonFromXml();

                messageJson = json.ToObject <GetFolderResult>();
                if (messageJson.totalSize == 0)  //no messages
                {
                    return(null);
                }
                else
                {
                    var messages = result.GetMessagesResponsesFromXml();
                    VariableCollection delete = new VariableCollection();

                    XmlDocument xmlResponse = new XmlDocument();
                    xmlResponse.LoadXml(result);
                    string responseXml = xmlResponse.SelectSingleNode("/response/html").InnerText;
                    var    doc         = new HtmlDocument();
                    doc.LoadHtml(responseXml);
                    var messageId = doc.DocumentNode.SelectSingleNode("//div").Attributes["id"].Value;
                    delete["messages"].Value = messageId;
                    delete["archive"].Value  = 1;
                    delete["_rnr_se"].Value  = rnr_se;

                    string archive_url = Regex.Replace(base_url, "/recent", "") + "archiveMessages/";
                    var    response    = WebClient.Post(archive_url, delete);
                    return(messages);
                }
            } catch (Exception ex) {
                throw new FolderException(get_url, ex);
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Sends a SMS message to the destination phone number with the specified message
        /// </summary>
        public bool SMS(string destinationPhoneNumber, string message)
        {
            try
            {
                VariableCollection parameters = GenerateParameters();

                parameters["phoneNumber"].Value  = destinationPhoneNumber;
                parameters["text"].Value         = message;
                parameters["sendErrorSms"].Value = 0;
                parameters["_rnr_se"].Value      = Session;

                var result = WebClient.Post(GenerateUrl(), parameters);

                GetFolderResult returnValue = new GetFolderResult();
                var             dictionary  = result.Content.ToObject <Dictionary <string, object> >();

                return(Convert.ToBoolean(dictionary["ok"]));
            }
            catch (Exception ex)
            {
                throw new SmsException(ex);
            }
        }
Esempio n. 17
0
        /// <summary>Changes the client seed which affects the outcome of bets.</summary>
        /// <param name="seed">The new seed to be used.</param>
        /// <returns>An awaitable <see cref="SeedSet"/> object if the client seed was changed successfully.</returns>
        public async Task <SeedSet> ChangeClientSeed(string seed = null)
        {
            // Generate a new client seed automatically if no seed was specified
            if (string.IsNullOrEmpty(seed))
            {
                seed = Utils.GenerateRandomClientSeed();
            }

            if (WebClient.IsAuthorized)
            {
                // Change the client seed on the server
                var response = await WebClient.Post <ServerResponse>("seed", new Dictionary <string, string> {
                    ["seed"] = seed
                });

                return(response.SeedSet);
            }
            else
            {
                // Change the client seed locally
                SimulatedSeedSet.ClientSeed = seed;
                return(SimulatedSeedSet);
            }
        }
Esempio n. 18
0
        public AcessTokenandOpendid getUserInfo()
        {
            WebClient webClient = WebClient.instance;
            String    param     = Consts.GET_ACCESS_TOKEN_AND_OPENID + getParams();

            try
            {
                String userInfo = webClient.Post(param, "", "");
                return(getAcessToken(userInfo));
            }
            catch (Exception ex)
            {
                if (currentTryRunNum == TRY_AGAIN_MUN)
                {
                    FailRequestManager.mInstance.saveInFailList(mModel.UserID, Convert.ToDateTime(mSyncDay), param, (ex == null ? "" : ex.Message));
                    return(null);
                }
                else
                {
                    currentTryRunNum++;
                    return(getUserInfo());
                }
            }
        }
Esempio n. 19
0
        public void TestMethods()
        {
            var data = new Dictionary <string, string> {
                { "MyKey", "MyValue" }
            };

            using (var client = new WebClient()) {
                var getHttpResponse = client.Get(_url);
                var getHttpData     = getHttpResponse.ToString().Trim();
                var getMethod       = getHttpResponse.Headers.GetValues("Method").FirstOrDefault();
                Assert.AreEqual("GET", getMethod);
                Assert.AreEqual("SUCCESS", getHttpData);

                var postContent      = WebRequest.JsonContent(data);
                var postContentStr   = postContent.ReadAsStringAsync().Result;
                var postHttpResponse = client.Post(_url, postContent);
                var postData         = postHttpResponse.ToString().Trim();
                var postMethod       = postHttpResponse.Headers.GetValues("Method").FirstOrDefault();
                Assert.AreEqual("POST", postMethod);
                Assert.AreEqual(postContentStr, postData);

                var putContent      = WebRequest.FormContent(data);
                var putContentStr   = putContent.ReadAsStringAsync().Result;
                var putHttpResponse = client.Put(_url, putContent);
                var putData         = putHttpResponse.ToString().Trim();
                var putMethod       = putHttpResponse.Headers.GetValues("Method").FirstOrDefault();
                Assert.AreEqual("PUT", putMethod);
                Assert.AreEqual(putContentStr, putData);

                var deleteResponse = client.Delete(_url);
                var deleteData     = deleteResponse.ToString().Trim();
                var deleteMethod   = deleteResponse.Headers.GetValues("Method").FirstOrDefault();
                Assert.AreEqual("DELETE", deleteMethod);
                Assert.AreEqual("SUCCESS", deleteData);
            }
        }
Esempio n. 20
0
        private bool Save(string query, T entity, PostUpdateType updateType)
        {
            var path        = GenerateGetPath(HttpMethods.POST, query);
            var strContent  = JsonConvert.SerializeObject(entity);
            var postRequest = new PostRequest()
            {
                filter       = query,
                updatetype   = updateType.ToString(),
                updateObject = strContent
            };

            strContent = JsonConvert.SerializeObject(postRequest);

            var ret = WebClient.Post(path, strContent);

            if (ret != null)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Esempio n. 21
0
 public void Create(Participant participant)
 {
     WebClient client = new WebClient();
     participant = client.Post<Participant, Participant>(string.Format("tournaments/{0}/participants.json", participant.TournamentId), participant);
 }
Esempio n. 22
0
        /*public object GetLast30OfSite()
         * {
         *  return null;
         * }*/

        /// <summary>Creates a new <see cref="Bet"/> on the server, or a simulated one if the current <see cref="PrimediceClient"/> is not authenticated.</summary>
        /// <param name="amount">Amount of satoshi to bet.</param>
        /// <param name="condition">Condition of the bet, relative to <paramref name="target"/>.</param>
        /// <param name="target">Target of the dice roll.</param>
        /// <returns>An awaitable <see cref="Bet"/> object if the bet was placed successfully.</returns>
        public async Task <Bet> Create(double amount, BetCondition condition, float target)
        {
            // Round the target automatically
            target = (float)Math.Round(target, 2, MidpointRounding.AwayFromZero);

            if (WebClient.IsAuthorized)
            {
                // Create a new bet on the server
                var response = await WebClient.Post <ServerResponse>("bet", new Dictionary <string, string> {
                    ["amount"]    = amount.ToString(CultureInfo.InvariantCulture),
                    ["target"]    = target.ToString(CultureInfo.InvariantCulture),
                    ["condition"] = condition.ToJsonString()
                });

                return(response.Bet);
            }
            else
            {
                // Create a new simulated bet
                var bet = new Bet {
                    IsSimulated      = true,
                    ServerSeedHashed = SimulatedSeedSet.ServerSeedHashed,
                    ClientSeed       = SimulatedSeedSet.ClientSeed,
                    Nonce            = SimulatedSeedSet.Nonce,
                    Time             = DateTime.UtcNow,
                    Amount           = amount,
                    Condition        = condition,
                    Target           = target
                };

                // Calculate the roll of the bet
                var roll = bet.CalculateRoll(SimulatedSeedSet.ServerSeed);
                bet.Roll = roll;

                // Determine whether the bet was won or lost and calculate the multiplier
                bool  isWon;
                float multiplier;
                if (condition == BetCondition.LowerThan)
                {
                    isWon      = roll < target;
                    multiplier = 100 / target * (1 - Utils.HouseEdge);
                }
                else
                {
                    isWon      = roll > target;
                    multiplier = 100 / (100 - target) * (1 - Utils.HouseEdge);
                }
                multiplier = (float)Math.Floor(multiplier * 100000) / 100000;

                // Set the properties of the bet
                bet.IsWon      = isWon;
                bet.Multiplier = multiplier;
                if (isWon)
                {
                    bet.ProfitAmount = amount * (multiplier - 1);
                }
                else
                {
                    bet.ProfitAmount = -amount;
                }

                // Generate a new server seed and reset nonce to 0 if necessary
                if (SimulatedSeedSet.Nonce == ulong.MaxValue)
                {
                    SimulatedSeedSet.Nonce = 0;

                    var nextServerSeed = Utils.GenerateRandomServerSeed();
                    SimulatedSeedSet.PreviousServerSeed       = SimulatedSeedSet.ServerSeed;
                    SimulatedSeedSet.PreviousServerSeedHashed = SimulatedSeedSet.ServerSeedHashed;
                    SimulatedSeedSet.ServerSeed           = SimulatedSeedSet.NextServerSeed;
                    SimulatedSeedSet.ServerSeedHashed     = SimulatedSeedSet.NextServerSeedHashed;
                    SimulatedSeedSet.NextServerSeed       = nextServerSeed;
                    SimulatedSeedSet.NextServerSeedHashed = nextServerSeed.GetHashed();
                }
                else
                {
                    // Increment the simulated nonce by 1
                    SimulatedSeedSet.Nonce += 1;
                }

                // Return the simulated bet object
                return(bet);
            }
        }
Esempio n. 23
0
        static void Main(string[] args)
        {
            // ListExtensions.cs
            Console.WriteLine("ListExtensions.cs Examples");

            // AreAllFactorsOf
            List <int> factorsList = new List <int>()
            {
                2, 5, 10
            };

            Console.WriteLine("AreAllFactorsOf - Example: " + factorsList.AreAllFactorsOf(20)); // True

            // ContainsAnyLettersFrom
            List <char> charListA = new List <char> {
                'a', 'b', 'c'
            };
            List <char> charListB = new List <char> {
                'd', 'e', 'f'
            };
            List <char> charListC = new List <char> {
                'g', 'h', 'b'
            };

            Console.WriteLine("ContainsAnyLettersFrom - Example 1: " + charListA.ContainsAnyLettersFrom(charListB)); // False
            Console.WriteLine("ContainsAnyLettersFrom - Example 2: " + charListA.ContainsAnyLettersFrom(charListC)); // True

            // Median
            List <double> medianList = new List <double>()
            {
                1, 2, 3, 4, 5
            };

            Console.WriteLine("Median - Example: " + medianList.Median()); // 3
            Console.WriteLine();


            // StringExtensions.cs
            Console.WriteLine("StringExtensions.cs Examples");

            // IsAPalindrome
            string notAPalindrome = "Some String";
            string isAPalindrome  = "Some emoS";

            Console.WriteLine("IsAPalindrome - Example 1: " + notAPalindrome.IsAPalindrome());
            Console.WriteLine("IsAPalindrome - Example 2: " + isAPalindrome.IsAPalindrome());

            // IsAPangram
            string notAPangram = "This is not a pangram";
            string isAPangram  = "The quick brown fox jumps over the lazy dog";

            Console.WriteLine("IsAPangram - Example 1: " + notAPangram.IsAPangram()); // False
            Console.WriteLine("IsAPangram - Example 2: " + isAPangram.IsAPangram());  // True

            // Reverse
            string reversedString = "dlroW olleH";

            Console.WriteLine("Reverse - Example: " + reversedString.Reverse()); // Hello World

            // ToCharList
            string      someString = "Hello World";
            List <char> charList   = someString.ToCharList();

            Console.WriteLine("ToCharList - Example: " + charList.Count); // 11

            // RemoveUntil
            string longString = "This is some data we don't need and a search point. Important Text Here";

            Console.WriteLine("RemoveUntil - Example 1: " + longString.RemoveUntil("point. ", false)); // "point. Important Text Here"
            Console.WriteLine("RemoveUntil - Example 2: " + longString.RemoveUntil("point. ", true));  // "Important Text Here"

            // Mostly Cryptography stuff
            // ToBase64
            Console.WriteLine("ToBase64 - Example: " + "Hello World!!".ToBase64()); // SGVsbG8gV29ybGQhIQ==

            // FromBase64
            Console.WriteLine("FromBase64 - Example: " + "SGVsbG8gV29ybGQhIQ==".FromBase64()); // Hello World!!

            // ToROT13
            Console.WriteLine("ToROT13 - Example: " + "Uryyb Jbeyq!".ToROT13()); // Hello World!

            // ToSHA1
            Console.WriteLine("ToSHA1 - Example: " + "Hello World!".ToSHA1()); // 2ef......871

            // ToSHA512 (The result is 128 characters long and will likely overflow onto a 2nd display line)
            Console.WriteLine("ToSHA512 - Example: " + "Hello World!".ToSHA512()); // 861......cc8

            // VigenereDecrypt (Note: Key is case insensitive)
            Console.WriteLine("VigenereDecrypt - Example: " + "Yipww Tfvpo".VigenereDecrypt("Reelix")); // Hello World
            Console.WriteLine();

            Console.WriteLine("Press Enter to load the WebClient examples");
            Console.ReadLine();

            // WebClient.cs
            Console.WriteLine("Loading WebClient.cs examples...");
            WebClient wc = new WebClient();

            wc.SetForwarded("google.com");
            wc.SetVia("bob.com"); // Does not show in rest example
            string result = wc.Post("https://httpbin.org/anything", new List <string> {
                "postNameHere=postValueHere", "postNameHere2=postValueHere2"
            });

            Console.WriteLine("Post Test: \n" + result);
            Console.ReadLine();
        }
Esempio n. 24
0
 public void Create(Tournament tournament)
 {
     WebClient client = new WebClient();
     tournament = client.Post<TournamentPostRequest, Tournament>("tournaments.json", new TournamentPostRequest(tournament));
 }
Esempio n. 25
0
        /// <summary>
        /// 根据Web接口获取数据
        /// </summary>
        /// <param name="Request"></param>
        /// <param name="dwbm"></param>
        /// <param name="gh"></param>
        /// <param name="jsbm"></param>
        /// <param name="bmbm"></param>
        /// <returns></returns>
        public string GetWebService(System.Web.HttpRequest Request, string dwbm, string gh, string jsbm, string bmbm)
        {
            string url = ConfigHelper.GetConfigString("AJXXDZ");
            string key = "tyknntd-#4kji2%(+^";

            if (string.IsNullOrEmpty(url))
            {
                return(ReturnString.JsonToString(Prompt.error, "您已配置为外部连接方式,请先设置配置文件连接地址", null));
            }

            Dictionary <String, String> dicList = new Dictionary <String, String>();

            string page      = Request["page"];
            string rows      = Request["pagesize"];
            string bmsah     = Request["key"];
            string ajmc      = Request["casename"];
            string cbr       = Request["dutyman"];
            string timebegin = Request["timebegin"];
            string timeend   = Request["timeend"];
            //单位编码和案件类别
            string caseUnit = Request["caseUnit"];
            string caseAjlb = Request["caseajlb"];
            //排序
            string sortname  = Request["sortname"];
            string sortorder = Request["sortorder"];

            if (string.IsNullOrEmpty(sortname))
            {
                sortname  = "SLRQ DESC";
                sortorder = "";
            }
            if (sortname == "AJ_DWMC" || sortname == "CBDW_MC")
            {
                sortname = "CBDW_BM";
            }

            sortname += " " + sortorder;

            List <object> values = new List <object>();

            if (!string.IsNullOrEmpty(bmsah))
            {
                bmsah = "Bmsah=\"" + bmsah + "\"";
            }
            if (!string.IsNullOrEmpty(ajmc))
            {
                ajmc = "Ajmc=\"" + ajmc + "\"";
            }
            if (!string.IsNullOrEmpty(cbr))
            {
                cbr = "Cbr=\"" + cbr + "\"";
            }
            if (!string.IsNullOrEmpty(timebegin))
            {
                timebegin = "Timebegin=\"" + timebegin + "\"";
            }
            if (!string.IsNullOrEmpty(timeend))
            {
                timeend = "Timeend =\"" + timeend + "\"";
            }
            if (!string.IsNullOrEmpty(caseUnit))//单位编码
            {
                string[] dwbms    = caseUnit.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                string   dwbmParm = "";
                for (int i = 0; i < dwbms.Length; i++)
                {
                    dwbmParm += "{\"dwbm\":\"" + dwbms[i] + "\"}";
                    if (i < dwbms.Length - 1)
                    {
                        dwbmParm += ",";
                    }
                }
                caseUnit = "[" + dwbmParm + "]";
            }
            else
            {
                XT_DM_QX qx = new XT_DM_QX(Request);
                DataSet  ds = qx.GetDwList(jsbm, dwbm, bmbm, "");
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    DataTable dt = ds.Tables[0].Copy();
                    dt.Columns["QXBM"].ColumnName = "dwbm";
                    dt.Columns.Remove("QXMC");
                    caseUnit = JsonHelper.JsonString(dt);
                }
                else
                {
                    caseUnit = "[{\"dwbm\":\"" + dwbm + "\"}]";
                }
            }
            if (!string.IsNullOrEmpty(caseAjlb))//案件类别
            {
                string[] ajlb     = caseAjlb.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                string   ajlbParm = "";
                for (int i = 0; i < ajlb.Length; i++)
                {
                    ajlbParm += "{\"lb\":\"" + ajlb[i] + "\"}";
                    if (i < ajlb.Length - 1)
                    {
                        ajlbParm += ",";
                    }
                }
                caseAjlb = "[" + ajlbParm + "]";
            }
            else
            {
                XT_DM_QX qx = new XT_DM_QX(Request);
                DataSet  ds = qx.GetLBList(jsbm, dwbm, bmbm, "");
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    DataTable dt = ds.Tables[0].Copy();
                    dt.Columns["QXBM"].ColumnName = "lb";
                    dt.Columns.Remove("QXMC");
                    caseAjlb = JsonHelper.JsonString(dt);
                }
                //else
                //    caseAjlb = "[{\"ajlbbm\":\"" + dwbm + "\"}]";
            }

            dicList.Add("PageIndex", page);
            dicList.Add("PageSize", rows);
            dicList.Add("Bmsah", bmsah);
            dicList.Add("MC", ajmc);
            //dicList.Add("Cbr", cbr);
            dicList.Add("Timebegin", timebegin);
            dicList.Add("Timeend", timeend);
            dicList.Add("DWBM", caseUnit.Replace("\r\n", ""));
            dicList.Add("LB", caseAjlb.Replace("\r\n", ""));
            //dicList.Add("Sort", sortname);

            //dicList.Add("PageIndex", (string.IsNullOrEmpty(page) ? page : EDRS.Common.DEncrypt.DEncrypt.Encrypt(page, key)));
            //dicList.Add("PageSize", (string.IsNullOrEmpty(rows) ? rows : EDRS.Common.DEncrypt.DEncrypt.Encrypt(rows, key)));
            //dicList.Add("Bmsah", (string.IsNullOrEmpty(bmsah) ? bmsah : EDRS.Common.DEncrypt.DEncrypt.Encrypt(bmsah, key)));
            //dicList.Add("Ajmc", (string.IsNullOrEmpty(ajmc) ? ajmc : EDRS.Common.DEncrypt.DEncrypt.Encrypt(ajmc, key)));
            //dicList.Add("Cbr", (string.IsNullOrEmpty(cbr) ? cbr : EDRS.Common.DEncrypt.DEncrypt.Encrypt(cbr, key)));
            //dicList.Add("Timebegin", (string.IsNullOrEmpty(timebegin) ? timebegin : EDRS.Common.DEncrypt.DEncrypt.Encrypt(timebegin, key)));
            //dicList.Add("Timeend", (string.IsNullOrEmpty(timeend) ? timeend : EDRS.Common.DEncrypt.DEncrypt.Encrypt(timeend, key)));
            //dicList.Add("Dwbm", (string.IsNullOrEmpty(caseUnit) ? caseUnit : EDRS.Common.DEncrypt.DEncrypt.Encrypt(caseUnit, key)));
            //dicList.Add("Ajlbbm", (string.IsNullOrEmpty(caseAjlb) ? caseAjlb : EDRS.Common.DEncrypt.DEncrypt.Encrypt(caseAjlb, key)));
            //dicList.Add("Sort", (string.IsNullOrEmpty(sortname) ? sortname : EDRS.Common.DEncrypt.DEncrypt.Encrypt(sortname, key)));

            WebClient wc = new WebClient();
            string    rt = wc.Post(url, dicList);

            if (!string.IsNullOrEmpty(rt))
            {
                string stat = JsonHelper.DeserializeObjectKey("[" + rt + "]", "Stat");
                if (stat == "0")
                {
                    string    data   = JsonHelper.DeserializeObjectKey("[" + rt + "]", "Data");
                    DataTable dtData = JsonHelper.ToDataTable(data);
                    if (dtData != null)
                    {
                        dtData.Columns["MC"].ColumnName   = "AJMC";
                        dtData.Columns["BH"].ColumnName   = "BMSAH";
                        dtData.Columns["LBMC"].ColumnName = "AJLB_MC";
                        dtData.Columns["LBBM"].ColumnName = "AJLB_BM";
                        dtData.Columns["DWMC"].ColumnName = "CBDW_MC";
                        dtData.Columns["DWBM"].ColumnName = "CBDW_BM";


                        if (dtData.Rows.Count > 0)
                        {
                            return("{\"Total\":" + dtData.Rows[0]["Total"].ToString() + ",\"Rows\":" + JsonHelper.JsonString(dtData) + "}");
                        }
                    }
                    //{
                    //Total:分页数据总数(int),
                    //MC:名称(string),
                    //BH:编号(string),
                    //LBMC:类别名称(string),
                    //LBBM:类别编码(string),
                    //DWMC:单位名称(string),
                    //DWBM:单位编码(string),
                    //CBR:承办人(string),
                    //SLRQ:受理日期(yyyy-MM-dd HH:mm:ss)
                    //}
                    //  "{"Total":1,"Rows":[{"ISREGARD": 0,  "AJMC": "ffffff",  "BMSAH": "广元市公安局上会议题[2016]37000000001号",  "AJLB_MC": "上会议题",  "CBDW_MC": "广元市公安局",  "CBBM_MC": null,  "CBR": null,  "DQJD": null,  "SLRQ": "2016-04-05 11:15:36",  "AJZT": "0",  "DQRQ": "1900-01-01 00:00:00",  "BJRQ": "1900-01-01 00:00:00",  "WCRQ": "1900-01-01 00:00:00",  "GDRQ": "1900-01-01 00:00:00",  "AJLB_BM": "1101",  "CBDW_BM": "370000",  "XYR": "ff",  "SFZH": "444444444444444444",  "TARYXX": "asdfasdfasdfasd"}]}"
                }
                else if (stat == "1")
                {
                    string msg = JsonHelper.DeserializeObjectKey("[" + rt + "]", "Msg");
                    return(ReturnString.JsonToString(Prompt.error, msg, null));
                }
            }
            return(ReturnString.JsonToString(Prompt.error, "未找到信息", null));
        }
Esempio n. 26
0
 public static Task <HttpResponseMessage> RegisterAgent(AgentConfig agentConfig)
 {
     return(WebClient.Post(MasterRoute.RegisterAgent, agentConfig));
 }
Esempio n. 27
0
        /// <summary>
        /// 检查网站激活状态
        /// </summary>
        internal static void CheckActiveState()
        {
            object checkCache =Cms.Cache.Get(checkKey);
                
            if (checkCache == null)
            {
                try
                {
                    //如果Key为空则Key为temp.ops.cc产生的Key
                    string key = Settings.License_KEY 
                          ?? "YmIyNDAwMGI3YmEyZGMwZTgxZWI2OGQxYzk3MWU4NWI=";

                    WebClient client = new WebClient("http://ct.ops.cc/ct/license");
                    string responseText = client.Post(
                        "token=YmIyNDAwMGI3YmEyZGMwZTgxZWI2OGQxYzk3MWU4NWI&license_key="
                        + key + "&license_name=" + Settings.License_NAME);

                    activeInfo = responseText;
                }
                catch
                {
                    //如果校验服务器请求产生问题,则不检测激活状态
                    //activeInfo = null;
                    //activeInfo = ex.Message;
                }
            }
        }