Beispiel #1
1
 /// <summary>
 /// 创建应用菜单
 /// </summary>
 /// <param name="accessToken">调用接口凭证</param>
 /// <param name="agentid">企业应用的id,整型。可在应用的设置页面查看</param>
 /// <param name="m">菜单信息</param>
 /// <returns></returns>
 public WeChatResult Create(string accessToken, int agentid, List<MenuCreate> m)
 {
     var data = from a in m select new { type = a.Type.ToString(), name = a.Name, key = a.Key, url = a.Url, sub_button = from p in a.SubMenu select new { type = p.Type.ToString(), name = p.Name, key = p.Key, url = p.Url } };
     var dataTmp = new { button = data };
     var dataJson = JsonConvert.SerializeObject(dataTmp);
     var resultJson = HttpHelper.PostString(EntRequestUrl.CreateMenu.ToUrl(accessToken, agentid), dataJson);
     WeChatResult result = JsonConvert.DeserializeObject<WeChatResult>(resultJson);
     return result;
 }
        public async Task<JsonResult> Test(QueryData c)
        {
            using (var client = new HttpClient())
            {
                 List<StringTable> all = null;
                 all = new List<StringTable>();
                #region Post
                var scoreRequest = new
                {

                    Inputs = new Dictionary<string, StringTable>() { 
                        { 
                            "input1", 
                            new StringTable() 
                            {
                                //ColumnNames = new string[] {"Pclass", "Sex", "Age", "Embarked"},
                                Values = new string[,] {  { c.Pclass.ToString(), c.Sex, c.Age.ToString(), c.Embarked }  }
                            }
                        },
                    },
                    GlobalParameters = new Dictionary<string, string>()
                    {
                    }
                };
                const string apiKey = "zGEEXM7Ua9r4cT1/CEMm8E2S/CF2xGcrqvRD3ilEG8WTCe7QAJy0OHwBoxDXCofcexXuH5xk4V2XX3H6AkvBqw=="; // Replace this with the API key for the web service
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);

                client.BaseAddress = new Uri("https://ussouthcentral.services.azureml.net/workspaces/331acdcb3e9b4bd2836d4eb003c2f372/services/721d99cb94cb4c92a7c14f1a92846649/execute?api-version=2.0&details=true");

                HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest);
                #endregion
               
                if (response.IsSuccessStatusCode)
                {
                    string result = await response.Content.ReadAsStringAsync();
                    //JObject o = JObject.Parse(result);
                    return Json(result, JsonRequestBehavior.AllowGet);
                }
                #region else
                else
                {
                    Console.WriteLine(string.Format("The request failed with status code: {0}", response.StatusCode));
                    return Json(response.StatusCode, JsonRequestBehavior.AllowGet);
                    // Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure
                    //Console.WriteLine(response.Headers.ToString());

                    string responseContent = await response.Content.ReadAsStringAsync();
                    
                  
                    return Json(responseContent, JsonRequestBehavior.AllowGet);
                }
                return Json("hello world", JsonRequestBehavior.AllowGet);
                #endregion
            }
               
        }
Beispiel #3
0
 /// <summary>
 /// 返回成功的Json数据
 /// </summary>
 public JsonResult JsonSuccess(string msg = "")
 {
     var json = new
     {
         valid = true,
         msg = msg
     };
     return Json(json, JsonRequestBehavior.AllowGet);
 }
Beispiel #4
0
 /// <summary>
 /// 返回失败的Json数据
 /// </summary>
 public JsonResult JsonError(string msg = "")
 {
     var json = new
     {
         valid = false,
         msg = msg
     };
     return Json(json, JsonRequestBehavior.AllowGet);
 }
 private async void AddUserRole_Click(object sender, RoutedEventArgs e)
 {
     if (UserRoleNameWillBeAdded.Text != "")
     {
         string name = UserRoleNameWillBeAdded.Text;
         var obj = new { Name = name };
         await UserRoleManager.AddUserRole(new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json"), UserRoles);
     }
 }
Beispiel #6
0
        public JsonResult GetData()
        {
            var vm = new
            {
                GenreList = GetGenreList(),
                TableColumnList = _common.GetTableColumnList(_currentUser.Id, Constants.UserTable.GenreId)
            };

            return Json(vm, JsonRequestBehavior.AllowGet);
        }
 private async void AddOption_Click(object sender, RoutedEventArgs e)
 {
     if (OptionTitleWillBeAdded.Text != "")
     {
         bool active = ((string)OptionActiveWillBeAdded.SelectionBoxItem == "Yes") ? true : false;
         string title = OptionTitleWillBeAdded.Text;
         var obj = new { Title = title, IsActive = active };
         await OptionManager.AddOption(new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json"), Options);
     }
 }
 public async Task CompleteRepairAssignmentTaskAsync(int incidentId)
 {
     var taskId = await GetTaskIdAsync(incidentId);
     var value = new
     {
         Status = "Completed",
         PercentComplete = 1
     };
     await UpdateTaskAsync(taskId, value);
 }
        public void MutablePagedList()
        {
            var items = new[] { "1", "2", "3" };
            var originalObject = new MutablePagedList<string>(items);
            var expectedJson = JsonConvert.SerializeObject(originalObject, _settings);

            var deserializedObject = JsonConvert.DeserializeObject<MutablePagedList<string>>(expectedJson, _settings);
            var actualJson = JsonConvert.SerializeObject(deserializedObject, _settings);

            Assert.Equal(expectedJson, actualJson);
        }
 public async Task CompleteRepairApprovalTask(int incidentId, ApprovalResult result)
 {
     var taskId = await GetTaskId(incidentId);
     var value = new
     {
         Status = "Completed",
         PercentComplete = 1,
         TaskOutcome = result.ToString()
     };
     await UpdateTask(taskId, value);
 }
 public async Task CompleteRepairApprovalTaskAsync(AuditRepairModel model)
 {
     var taskId = await GetTaskIdAsync(model.IncidentId);
     var value = new
     {
         Status = "Completed",
         PercentComplete = 1,
         TaskOutcome = model.Result.ToString()
     };
     await UpdateTaskAsync(taskId, value);
 }
        public IHttpActionResult GetCacheBuildings()
        {
            int isTimingSettle = Convert.ToInt32(WebConfigHelper.ReadAppSetting("IsTimingSettle"));
            var buildings = TextHelper.GetCacheBuildings(this.buildingRepository, this.roomRepository);
            var items = new
            {
                IsTimingSettle = isTimingSettle,
                Buildings = buildings
            };

            return Ok(items);
        }
Beispiel #13
0
        public JsonResult GetData()
        {
            var vm = new
            {
                BandList = GetBandList(),
                DefaultSingerArrayList = _bandRepository.GetDefaultSingerNameArrayList(),
                DefaultGenreArrayList = _bandRepository.GetDefaultGenreArrayList(),
                TableColumnList = _common.GetTableColumnList(_currentUser.Id, Constants.UserTable.BandId)
            };

            return Json(vm, JsonRequestBehavior.AllowGet);
        }
Beispiel #14
0
        public JsonResult GetData()
        {
            var bandId = Convert.ToInt32(Session["BandId"]);
            var vm = new
            {
                GigList = GetGigList(bandId),
                SetlistArrayList = _setlistRepository.GetSetlistArrayList(bandId),
                TableColumnList = _common.GetTableColumnList(_currentUser.Id, Constants.UserTable.GigId, bandId)
            };

            return Json(vm, JsonRequestBehavior.AllowGet);
        }
 public static string V0()
 {
     var json = new
     {
         Schema = "Person", // 'versioned' 'type' of structure
         Version = 0, // 'versioned' 'type' of structure
         Payload = new {
             Name = "joe"
         }
     };
     return JsonConvert.SerializeObject(json);
 }
        public static async Task<string> InvokeRequestResponseService(StringTable p)
        {
            using (var client = new HttpClient())
            {
                var scoreRequest = new
                {
                    Inputs = new Dictionary<string, StringTable>() {
                        {"input1",p},
                        {"input6",p},
                        {"input3",p},
                        {"input4",p},
                        {"input5",p},
                        {"input2",p},
                        {"input7",p},
                        {"input8",p},
                    },
                    GlobalParameters = new Dictionary<string, string>()
                    {
                    }
                };

                const string apiKey = "hAKcxgPQ4MFs3p/FrjQ8EHJHowGgiyuVY3fSub7hOLKbA7W1mM3QkDjVqZBzOulRyHD0IQlXzU5wwJYpEX8Crw=="; // Replace this with the API key for the web service
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);

                client.BaseAddress = new Uri("https://ussouthcentral.services.azureml.net/workspaces/c5e785c7a67741039a35c221563ad7ef/services/2f7410441b1748f09fe976688203b080/execute?api-version=2.0&details=true");

                var content = JsonConvert.SerializeObject(scoreRequest);

                HttpResponseMessage response = await client.PostAsync("", new StringContent(content, Encoding.UTF8, "application/json"));

                if (response.IsSuccessStatusCode)
                {
                    string result = await response.Content.ReadAsStringAsync();

                    return result;
                    //dynamic res = JsonConvert.DeserializeObject(result);
                    //Console.WriteLine("Result: {0}", result);
                }
                else
                {
                    //Console.WriteLine(string.Format("The request failed with status code: {0}", response.StatusCode));

                    // Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure
                    //Console.WriteLine(response.Headers.ToString());

                    //string responseContent = await response.Content.ReadAsStringAsync();
                    //Console.WriteLine(responseContent);
                }
            }

            return String.Empty;
        }
Beispiel #17
0
        public async Task GetLeagueEntriesBySummonerIdsAsyncTest()
        {
            IRiotClient client = new RiotClient();
            var summonerIds = new[] { 35870943L, 34172230L };
            var leagues = await client.GetLeagueEntriesBySummonerIdsAsync(summonerIds);

            Assert.That(leagues, Is.Not.Null);
            foreach (var id in summonerIds)
                Assert.That(leagues.ContainsKey(id.ToString(CultureInfo.InvariantCulture)));
            var league = leagues.Values.First().First();
            Assert.That(league.Entries.Count, Is.EqualTo(1));
            Assert.That(league.Name, Is.Not.Null.And.Not.Empty);
        }
Beispiel #18
0
        public async Task<bool> Register(string username, string password, string repeatPassword)
        {
            var data = new
            {
                Email = username,
                Password = password,
                ConfirmPassword = repeatPassword
            };

            var result = await HttpHelper.PostData<object>("api/Account/Register", data);
            //TODO!
            return true;
        }
Beispiel #19
0
        public async Task GetLeagueEntriesByTeamIdsAsyncTest()
        {
            IRiotClient client = new RiotClient();
            var teamIds = new[] { "TEAM-3503e740-b492-11e3-809d-782bcb4d0bb2", "TEAM-2a88df50-da0d-11e3-b43f-782bcb4d1861" };
            var leagues = await client.GetLeagueEntriesByTeamIdsAsync(teamIds);

            Assert.That(leagues, Is.Not.Null);
            foreach (var id in teamIds)
                Assert.That(leagues.ContainsKey(id));
            var league = leagues.Values.First().First();
            Assert.That(league.Entries.Count, Is.EqualTo(1));
            Assert.That(league.Name, Is.Not.Null.And.Not.Empty);
        }
        internal BattleDetailRecords(SQLiteConnection rpConnection, int rpUserID) : base(rpConnection)
        {
            r_Filename = new FileInfo(Path.Combine(RecordService.Instance.RecordDirectory.FullName, rpUserID + "_Battle.db")).FullName;
            r_Connection = new SQLiteConnection($@"Data Source={r_Filename}; Page Size=8192").OpenAndReturn();

            using (var rCommand = r_Connection.CreateCommand())
            {
                rCommand.CommandText =
                    "PRAGMA journal_mode = DELETE; " +
                    "PRAGMA foreign_keys = ON;";

                rCommand.ExecuteNonQuery();
            }

            var rSortieFirstStageApis = new[]
            {
                "api_req_sortie/battle",
                "api_req_battle_midnight/sp_midnight",
                "api_req_sortie/airbattle",
                "api_req_sortie/ld_airbattle",
                "api_req_combined_battle/airbattle",
                "api_req_combined_battle/battle",
                "api_req_combined_battle/battle_water",
                "api_req_combined_battle/sp_midnight",
                "api_req_combined_battle/ld_airbattle",
                "api_req_combined_battle/ec_battle",
                "api_req_combined_battle/each_battle",
                "api_req_combined_battle/each_battle_water",
            };
            DisposableObjects.Add(ApiService.Subscribe(rSortieFirstStageApis, ProcessSortieFirstStage));
            DisposableObjects.Add(ApiService.Subscribe("api_req_practice/battle", ProcessPracticeFirstStage));

            var rSecondStageApis = new[]
            {
                "api_req_practice/midnight_battle",
                "api_req_battle_midnight/battle",
                "api_req_combined_battle/midnight_battle",
                "api_req_combined_battle/ec_midnight_battle",
                "api_req_practice/midnight_battle",
            };
            DisposableObjects.Add(ApiService.Subscribe(rSecondStageApis, ProcessSecondStage));

            var rBattleResultApis = new[]
            {
                "api_req_sortie/battleresult",
                "api_req_combined_battle/battleresult",
                "api_req_practice/battle_result",
            };
            DisposableObjects.Add(ApiService.Subscribe(rBattleResultApis, ProcessResult));
        }
Beispiel #21
-1
        public override void ExecuteResult(ControllerContext context)
        {
            // Set desired serializer options
            var serializerOptions = new JsonSerializerSettings
            {
                FloatFormatHandling = FloatFormatHandling.DefaultValue,
                TypeNameHandling = TypeNameHandling.None,
                NullValueHandling = NullValueHandling.Include,
                ContractResolver = new CamelCasePropertyNamesContractResolver { }
            };

            // Build desired output object
            var jsonData = new
            {
                status = this.StatusCode.ToString(),
                data = this.Data
            };

            // Serialize data
            var result = JsonConvert.SerializeObject(jsonData, Formatting.Indented, serializerOptions);

            // Write out result
            context.HttpContext.Response.StatusCode = (int)this.StatusCode;
            context.HttpContext.Response.ContentType = this.ContentType;
            context.HttpContext.Response.Write(result);
        }
Beispiel #22
-1
        /// <summary>
        /// 查询当天图文消息被阅读相关数据
        /// </summary>
        /// <param name="token"></param>
        /// <param name="startDate"></param>
        /// <returns></returns>
        public string ReportAritcleDataOneDay(string token, DateTime startDate)
        {
            //Request Data
            string url = "https://api.weixin.qq.com/datacube/getarticlesummary?access_token=";
            string dateTime = startDate.ToString("yyyy-MM-dd");

            //Result Data
            string strResult = string.Empty;
            dynamic dnm = null;

            //提交的内容
            var postParam = new
            {
                begin_date = dateTime,
                end_date = dateTime
            };

            //请求
            using (WebClient wc = new WebClient())
            {
                Encoding enc = Encoding.UTF8;
                strResult = enc.GetString(wc.UploadData(new Uri(url + token), enc.GetBytes(JsonConvert.SerializeObject(postParam))));
            }

            return strResult;
        }
Beispiel #23
-1
        internal static int GetId()
        {
            var definition = new { Id = 0 };
            string jsonString = DownloadJsonString("https://api.guildwars2.com/v2/build");

            return JsonConvert.DeserializeAnonymousType(jsonString, definition).Id;
        }
        public void InstantiationTest()
        {
            // Given
            IContainer container = new Container();
            container.RegisterForApplication();
            var bodyDyn = new { username = "******", password = "******" };
            var jsonString = "{\"username\":\"admin\",\"password\":\"success-password\"}";
            
            // When (Deserialize with actual object
            var result1 = JsonConvert.DeserializeObject<AuthenticationRequest>(jsonString);
            
            // Then
            Assert.AreEqual(result1.Username, "admin");
            Assert.AreEqual(result1.Password, "success-password");
            Assert.IsInstanceOf<AuthenticationRequest>(result1);

            // When (Deserialize with Custom IOC converter
            var result2 = JsonConvert.DeserializeObject<IAuthenticationRequest>(jsonString, new JsonIocSerializer<IAuthenticationRequest>(container));

            // Then
            Assert.AreEqual(result2.Username, "admin");
            Assert.AreEqual(result2.Password, "success-password");
            Assert.IsInstanceOf<AuthenticationRequest>(result2);

            // When
            //var result = TestHelper.JsonBodyPost(RouterPattern.Security.Authenticate, bodyDyn);
            //AuthenticationRequest
            //JsonConvert.DeserializeObject<List<IPerson>>(json, new PersonConverter());
        }
 public async Task<DateTime?> DoCheckInOrOutAsync(string userName, string password)
 {
     var regexSuccessCheckIn = new Regex(@"success:\s*true");
     var checkInOrOutUri = new Uri(baseUri, "SaveTimmingEvent");
     var httpClient = new HttpClient();
     var checkinDateTime = await RemoteDatetimeAsync();
     try
     {
         var content = new Windows.Web.Http.HttpFormUrlEncodedContent(BuildHttpFormContentForCheckInOrOut(userName, password));
         var response = await httpClient.PostAsync(checkInOrOutUri, content);
         var responseContent = await response.Content.ReadAsStringAsync();
         var responseJson = FixJson(responseContent);
         var responseType = new { success = false, msg = new { type = 0, msg = "" } };
         var responseObject = JsonConvert.DeserializeAnonymousType(responseJson, responseType);
         if (IsCheckSaved((int)responseObject.msg.type) && responseObject.success)
         {
             return checkinDateTime;
         }
         else
         {
             return null;
         }
     }
     catch { }
     return null;
 }
Beispiel #26
-1
        public static void RegisterUserWithHue()
        {
            try
            {
                var client = new WebClient();

                //our uri to perform registration
                var uri = new Uri(string.Format("http://{0}/api", HueLightIp));

                //create our registration object, along with username and description
                var reg = new
                {
                    username = HueLightUser,
                    devicetype = "Coding4Fun Hue Kinect Light Project"
                };

                var jsonObj = JsonConvert.SerializeObject(reg);

                client.UploadStringCompleted += client_UploadStringCompleted;

                //Invoke a POST to the bridge
                client.UploadStringAsync(uri, jsonObj);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
Beispiel #27
-1
        public async Task Push(string data)
        {
            var requestObj = new
            {
                messages = new [] 
                {
                    new
                    {
                        body = data
                    }
                }
            };

            var requestJson = JsonConvert.SerializeObject(requestObj);
            var requestContent = new StringContent(requestJson);
            requestContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var request = new HttpRequestMessage(HttpMethod.Post, "messages")
            {
                Content = requestContent
            };

            var response = await HttpClient.SendAsync(request);
            var responseContent = await response.Content.ReadAsStringAsync();
            var responseObj = JsonConvert.DeserializeObject<IronIoPushResponse>(responseContent);
        }
Beispiel #28
-1
 /// <summary>
 /// 批量删除成员
 /// </summary>
 /// <param name="accessToken">调用接口凭证</param>
 /// <param name="userid">成员UserID列表。对应管理端的帐号</param>
 /// <returns></returns>
 public WeChatResult DeleteBatch(string accessToken, List<string> userid)
 {
     var data = new { useridlist = userid };
     var dataJson = JsonConvert.SerializeObject(data);
     var resultJson = HttpHelper.PostString(EntRequestUrl.DeleteUserBatch.ToUrl(accessToken), dataJson);
     WeChatResult result = JsonConvert.DeserializeObject<WeChatResult>(resultJson);
     return result;
 }
 private async void AddYearTerm_Click(object sender, RoutedEventArgs e)
 {
     string year = (string)YearWillBeAdded.SelectionBoxItem;
     string term = (string)TermWillBeAdded.SelectionBoxItem;
     bool isDefault = ((string)YearTermIsDefaultWillBeAdded.SelectionBoxItem == "Yes") ? true : false;
     var obj = new { Year = year, Term = term, IsDefault = isDefault };
     await YearTermManager.AddYearTerm(new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json"), YearTerms);
 }
Beispiel #30
-2
        public async Task<bool> RegisterUserAsync()
        {
            var url = "http://" + BridgeIp + "/api";
            var body = new { devicetype = DeviceType, username = AppKey };
            var bodyJson = JsonConvert.SerializeObject(body);
            Debug.WriteLine(bodyJson);
            
            try
            {
                HttpClient client = new HttpClient();
                HttpResponseMessage resp = await client.PostAsync(url, new StringContent(bodyJson));
                resp.EnsureSuccessStatusCode();

                // Try to parse JSON response
                var result = await resp.Content.ReadAsStringAsync();
                Debug.WriteLine(result);
                if (result.Contains("101"))
                {
                    return false;
                }
                else if(result.Contains("success"))
                {
                    return true;
                }

            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                return false;
            }

            return true;
        }