// TODO: Verify ClientRequest values. static async Task HandleRealmListTicketRequest(ClientRequest clientRequest, BnetSession session) { var paramIdentityValue = clientRequest.GetVariant("Param_Identity")?.BlobValue.ToStringUtf8(); var paramClientInfoValue = clientRequest.GetVariant("Param_ClientInfo")?.BlobValue.ToStringUtf8(); if (paramIdentityValue != null && paramClientInfoValue != null) { var realmListTicketIdentity = CreateObject<RealmListTicketIdentity>(paramIdentityValue, true); var realmListTicketClientInformation = CreateObject<RealmListTicketClientInformation>(paramClientInfoValue, true); session.GameAccount = session.Account.GameAccounts.SingleOrDefault(ga => ga.Id == realmListTicketIdentity.GameAccountId); if (session.GameAccount != null) { session.RealmListSecret = realmListTicketClientInformation.Info.Secret.Select(x => Convert.ToByte(x)).ToArray(); session.RealmListTicket = new byte[0].GenerateRandomKey(32); var realmListTicketResponse = new ClientResponse(); realmListTicketResponse.Attribute.Add(new Bgs.Protocol.Attribute { Name = "Param_RealmListTicket", Value = new Variant { BlobValue = ByteString.CopyFrom(session.RealmListTicket) } }); await session.Send(realmListTicketResponse); } } else session.Dispose(); }
public ClientResponse<Email> Create(string emailTemplateId, Email emailTemplate) { var clientResponse = new ClientResponse<Email>(); var response = HttpClient.PostAsJsonAsync(string.Format("{0}/EmailTemplates/{1}/Emails", RealmToken, emailTemplateId), emailTemplate).Result; clientResponse.StatusCode = response.StatusCode; if (response.IsSuccessStatusCode) clientResponse.Result = response.Content.ReadAsAsync<Email>().Result; else clientResponse.Message = response.Content.ReadAsStringAsync().Result; return clientResponse; }
public ClientResponse<EmailTemplate> Delete(string id) { var clientResponse = new ClientResponse<EmailTemplate>(); var response = HttpClient.DeleteAsync(ResourceUrl + "/" + id).Result; clientResponse.StatusCode = response.StatusCode; if (response.IsSuccessStatusCode) clientResponse.Result = response.Content.ReadAsAsync<EmailTemplate>().Result; else clientResponse.Message = response.Content.ReadAsStringAsync().Result; return clientResponse; }
public ClientResponse<EmailTemplate> Update(EmailTemplate emailTemplate) { var clientResponse = new ClientResponse<EmailTemplate>(); var response = HttpClient.PutAsJsonAsync(ResourceUrl + "/" + emailTemplate.Id, emailTemplate).Result; clientResponse.StatusCode = response.StatusCode; if (response.IsSuccessStatusCode) clientResponse.Result = response.Content.ReadAsAsync<EmailTemplate>().Result; else clientResponse.Message = response.Content.ReadAsStringAsync().Result; return clientResponse; }
public ClientResponse<IEnumerable<EmailTemplate>> All() { var clientResponse = new ClientResponse<IEnumerable<EmailTemplate>>(); var response = HttpClient.GetAsync(ResourceUrl).Result; clientResponse.StatusCode = response.StatusCode; if (response.IsSuccessStatusCode) clientResponse.Result = response.Content.ReadAsAsync<IEnumerable<EmailTemplate>>().Result; else clientResponse.Message = response.Content.ReadAsStringAsync().Result; return clientResponse; }
public ClientResponse<Email> GetById(string emailTemplateId, string id) { var clientResponse = new ClientResponse<Email>(); var response = HttpClient.GetAsync(string.Format("{0}/EmailTemplates/{1}/Emails/{2}", RealmToken, emailTemplateId, id)).Result; clientResponse.StatusCode = response.StatusCode; if (response.IsSuccessStatusCode) clientResponse.Result = response.Content.ReadAsAsync<Email>().Result; else clientResponse.Message = response.Content.ReadAsStringAsync().Result; return clientResponse; }
public ClientResponse<BasicRealm> CreateRealm(string name) { var clientResponse = new ClientResponse<BasicRealm>(); var response = HttpClient.PostAsJsonAsync(RealmUrl, name).Result; clientResponse.StatusCode = response.StatusCode; if (response.IsSuccessStatusCode) clientResponse.Result = response.Content.ReadAsAsync<BasicRealm>().Result; else clientResponse.Message = response.Content.ReadAsStringAsync().Result; return clientResponse; }
private void readBuffer(BinaryReader buffers) { byte flag = buffers.ReadByte(); int lens = ReadInt(buffers.ReadBytes(4)); if (lens > buffers.BaseStream.Length) { waitLen = lens; isWait = true; buffers.BaseStream.Position = 0; byte[] dd = new byte[buffers.BaseStream.Length]; //TODO 明显有问题,应该是lens byte[] temp = buffers.ReadBytes((int)buffers.BaseStream.Length); Array.Copy(temp, 0, dd, 0, (int)buffers.BaseStream.Length); if (sources == null) { sources = dd; } return; } int headcode = ReadInt(buffers.ReadBytes(4)); int uuid = ReadInt(buffers.ReadBytes(4)); int soundLen = ReadInt(buffers.ReadBytes(4)); if (flag == 1) { byte[] sound = buffers.ReadBytes(soundLen); ClientResponse response = new ClientResponse(); response.headCode = headcode; response.bytes = sound; response.message = uuid.ToString(); _onData(response); } if (buffers.BaseStream.Position < buffers.BaseStream.Length) { readBuffer(buffers); } }
public async Task <IActionResult> GetClient([FromRoute] int id) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var client = await _context.Clients.Include(u => u.User).Include(a => a.Events) .FirstOrDefaultAsync(a => a.Id == id); var response = new ClientResponse { FullName = client.User.FullName, Description = client.User.Description, Id = client.Id, Address = client.Address, Email = client.User.Email, PhoneNumber = client.User.PhoneNumber, UserName = client.User.UserName, Events = client.Events.Select(p => new EventResponse { Id = p.Id, Name = p.Name, Duration = p.Duration, EventDate = p.EventDate, People = p.People, Description = p.Description, }).ToList(), }; if (client == null) { return(NotFound()); } return(Ok(response)); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testComplexObjectJacksonSerialization() throws org.codehaus.jettison.json.JSONException //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: public virtual void testComplexObjectJacksonSerialization() { WebResource resource = client.resource(APP_BASE_PATH + PROCESS_DEFINITION_PATH + "/statistics"); ClientResponse response = resource.queryParam("incidents", "true").accept(MediaType.APPLICATION_JSON).get(typeof(ClientResponse)); JSONArray definitionStatistics = response.getEntity(typeof(JSONArray)); response.close(); assertEquals(200, response.Status); // invoice example instance assertEquals(2, definitionStatistics.length()); // check that definition is also serialized for (int i = 0; i < definitionStatistics.length(); i++) { JSONObject definitionStatistic = definitionStatistics.getJSONObject(i); assertEquals("org.camunda.bpm.engine.rest.dto.repository.ProcessDefinitionStatisticsResultDto", definitionStatistic.getString("@class")); assertEquals(0, definitionStatistic.getJSONArray("incidents").length()); JSONObject definition = definitionStatistic.getJSONObject("definition"); assertEquals("Invoice Receipt", definition.getString("name")); assertFalse(definition.getBoolean("suspended")); } }
public virtual void TestTaskIdCountersSlash() { WebResource r = Resource(); IDictionary <JobId, Org.Apache.Hadoop.Mapreduce.V2.App.Job.Job> jobsMap = appContext .GetAllJobs(); foreach (JobId id in jobsMap.Keys) { string jobId = MRApps.ToString(id); foreach (Task task in jobsMap[id].GetTasks().Values) { string tid = MRApps.ToString(task.GetID()); ClientResponse response = r.Path("ws").Path("v1").Path("mapreduce").Path("jobs"). Path(jobId).Path("tasks").Path(tid).Path("counters/").Accept(MediaType.ApplicationJson ).Get <ClientResponse>(); NUnit.Framework.Assert.AreEqual(MediaType.ApplicationJsonType, response.GetType() ); JSONObject json = response.GetEntity <JSONObject>(); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, json.Length()); JSONObject info = json.GetJSONObject("jobTaskCounters"); VerifyAMJobTaskCounters(info, task); } } }
public Contact Update(string id, ContactUpdate contact) { if (contact == null) { throw new ArgumentNullException(nameof(contact)); } if (contact == null) { throw new ArgumentNullException(nameof(contact)); } ClientResponse <Contact> result = null; String body = Serialize <ContactUpdate>(contact); if (string.IsNullOrEmpty(id)) { result = Post <Contact>(body); } else { result = Put <Contact>(body, resource: CONTACTS_RESOURCE + Path.DirectorySeparatorChar + id); } return(result.Result); }
public async Task Previous_NotFirstPage_ReturnsPreviousPage() { ClientResponse <IList <ModelBase> > paginatedResponse = UKFastClientTests.GetListResponse(new List <ModelBase>(), 3); ClientResponse <IList <ModelBase> > mockResponse = UKFastClientTests.GetListResponse(new List <ModelBase>(), 3); IUKFastClient client = Substitute.For <IUKFastClient>(); client.GetPaginatedAsync <ModelBase>("testresource", Arg.Any <ClientRequestParameters>()).Returns(x => { return(Task.Run(() => new Paginated <ModelBase>(client, "testresource", x.ArgAt <ClientRequestParameters>(1), mockResponse))); }); Paginated <ModelBase> paginated = new Paginated <ModelBase>(client, "testresource", new ClientRequestParameters() { Pagination = new ClientRequestPagination() { Page = 3 } }, paginatedResponse); Paginated <ModelBase> previous = await paginated.Previous(); Assert.AreEqual(2, previous.CurrentPage); }
string ClientResponseToContent(ClientResponse clientResponse) { var responseBody = ""; var responseSerializer = new XmlSerializer(typeof(Response)); using (var stream = new MemoryStream()) using (var writer = new StreamWriter(stream)) { var ns = new XmlSerializerNamespaces(); ns.Add("", ""); responseSerializer.Serialize(writer, clientResponse.Response, ns); stream.Position = 0; using var reader = new StreamReader(stream); responseBody = reader.ReadToEnd(); } if (string.IsNullOrEmpty(responseBody)) { throw new Exception("Response body is empty"); } return(responseBody); }
public virtual void TestTaskAttemptIdXML() { WebResource r = Resource(); IDictionary <JobId, Org.Apache.Hadoop.Mapreduce.V2.App.Job.Job> jobsMap = appContext .GetAllJobs(); foreach (JobId id in jobsMap.Keys) { string jobId = MRApps.ToString(id); foreach (Task task in jobsMap[id].GetTasks().Values) { string tid = MRApps.ToString(task.GetID()); foreach (TaskAttempt att in task.GetAttempts().Values) { TaskAttemptId attemptid = att.GetID(); string attid = MRApps.ToString(attemptid); ClientResponse response = r.Path("ws").Path("v1").Path("history").Path("mapreduce" ).Path("jobs").Path(jobId).Path("tasks").Path(tid).Path("attempts").Path(attid). Accept(MediaType.ApplicationXml).Get <ClientResponse>(); NUnit.Framework.Assert.AreEqual(MediaType.ApplicationXmlType, response.GetType()); string xml = response.GetEntity <string>(); DocumentBuilderFactory dbf = DocumentBuilderFactory.NewInstance(); DocumentBuilder db = dbf.NewDocumentBuilder(); InputSource @is = new InputSource(); @is.SetCharacterStream(new StringReader(xml)); Document dom = db.Parse(@is); NodeList nodes = dom.GetElementsByTagName("taskAttempt"); for (int i = 0; i < nodes.GetLength(); i++) { Element element = (Element)nodes.Item(i); VerifyHsTaskAttemptXML(element, att, task.GetType()); } } } } }
public async Task HandleRequest(ClientResponse response, WebSocket socket, string id) { try { switch (response.Type) { case "Message": await HandleMessages(response, id); break; case "Game": await HandleGameRequests(response, socket); break; default: throw new ArgumentException("Invalid response"); } } catch (ArgumentException) { CloseConnection(id, socket); } }
public ClientResponse EnvioEmail(Bean_mail beanMail) { ClientResponse clientResponse = new ClientResponse(); try { Tbl_parameter_det entidad_det = null; entidad_det = new Tbl_parameter_det() { paramter_cab = new Tbl_parameter_cab() { skey_cab = "SKEY_MAIL" } }; IEnumerable <Tbl_parameter_det> lista = new ParameterLogic().GetParameter_skey(entidad_det); Tbl_parameter_det user = lista.ToList().Where(x => x.skey_det.Equals("SKEY_MAIL_DET_USER")).FirstOrDefault(); Tbl_parameter_det clave = lista.Where(x => x.skey_det.Equals("SKEY_MAIL_DET_CLAVE")).FirstOrDefault(); Tbl_parameter_det smtp = lista.Where(x => x.skey_det.Equals("SKEY_MAIL_DET_SMTP")).FirstOrDefault(); Tbl_parameter_det puerto = lista.Where(x => x.skey_det.Equals("SKEY_MAIL_DET_PUERTO")).FirstOrDefault(); beanMail.puerto = int.Parse(puerto.tx_descripcion); beanMail.de = user.tx_descripcion; beanMail.para = beanMail.para; beanMail.clave = clave.tx_descripcion; beanMail.smtpServer = smtp.tx_descripcion; beanMail.body = beanMail.body; beanMail.asunto = beanMail.asunto; clientResponse = Mail.EnvioMailSegundo(beanMail); } catch (Exception ex) { clientResponse = Utilidades.ObtenerMensajeErrorWeb(ex); } return(clientResponse); }
public ClientResponse GetAnucionXId([FromUri] int id) { ClientResponse clientResponse = new ClientResponse(); try { Tbl_galeria_anuncio entidad = new Tbl_galeria_anuncio() { id_anuncio = id }; object initData = new { DetailleAnuncion = new AnuncioLogic().GetAnucionXId(id), ListCargarInicial = new GaleriaLogic().Get_galeria_x_id_anuncio(entidad) }; clientResponse.Status = "OK"; clientResponse.Data = initData; } catch (Exception ex) { clientResponse = Utilidades.ObtenerMensajeErrorWeb(ex); } return(clientResponse); }
public virtual void TestJobsQueryUser() { WebResource r = Resource(); ClientResponse response = r.Path("ws").Path("v1").Path("history").Path("mapreduce" ).Path("jobs").QueryParam("user", "mock").Accept(MediaType.ApplicationJson).Get < ClientResponse>(); NUnit.Framework.Assert.AreEqual(MediaType.ApplicationJsonType, response.GetType() ); JSONObject json = response.GetEntity <JSONObject>(); System.Console.Out.WriteLine(json.ToString()); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, json.Length()); JSONObject jobs = json.GetJSONObject("jobs"); JSONArray arr = jobs.GetJSONArray("job"); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 3, arr.Length()); // just verify one of them. JSONObject info = arr.GetJSONObject(0); Org.Apache.Hadoop.Mapreduce.V2.App.Job.Job job = appContext.GetPartialJob(MRApps. ToJobID(info.GetString("id"))); VerifyJobsUtils.VerifyHsJobPartial(info, job); }
public UserLegacy UpdateLastSeenAt(UserLegacy user, long timestamp) { if (user == null) { throw new ArgumentNullException(nameof(user)); } if (timestamp <= 0) { throw new ArgumentException("'timestamp' argument should be bigger than zero."); } String body = String.Empty; if (!String.IsNullOrEmpty(user.id)) { body = JsonConvert.SerializeObject(new { id = user.id, last_request_at = timestamp }); } else if (!String.IsNullOrEmpty(user.user_id)) { body = JsonConvert.SerializeObject(new { user_id = user.user_id, last_request_at = timestamp }); } else if (!String.IsNullOrEmpty(user.email)) { body = JsonConvert.SerializeObject(new { email = user.email, last_request_at = timestamp }); } else { throw new ArgumentException("you need to provide either 'user.id', 'user.user_id', 'user.email' to update a user's last seen at."); } ClientResponse <UserLegacy> result = null; result = Post <UserLegacy>(body); return(result.Result); }
public Tag Untag(String name, List <User> users) { if (String.IsNullOrEmpty(name)) { throw new ArgumentNullException(nameof(name)); } if (users == null) { throw new ArgumentNullException(nameof(users)); } if (!users.Any()) { throw new ArgumentException("'users' argument should include more than one user."); } ClientResponse <Tag> result = null; String body = CreateBody(name, true, users: users); result = Post <Tag>(body); return(result.Result); }
public Tag Untag(String name, List <Company> companies) { if (String.IsNullOrEmpty(name)) { throw new ArgumentNullException(nameof(name)); } if (companies == null) { throw new ArgumentNullException(nameof(companies)); } if (!companies.Any()) { throw new ArgumentException("'companies' argument should include more than one company."); } ClientResponse <Tag> result = null; String body = CreateBody(name, true, companies: companies); result = Post <Tag>(body); return(result.Result); }
public void LoginCallBack(ClientResponse response) { if (watingPanel != null) { watingPanel.SetActive(false); } SoundCtrl.getInstance().stopBGM(); SoundCtrl.getInstance().playBGM(); if (response.status == 1) { if (GlobalDataScript.homePanel != null) { GlobalDataScript.homePanel.GetComponent <HomePanelScript>().removeListener(); Destroy(GlobalDataScript.homePanel); } if (GlobalDataScript.gamePlayPanel != null) { GlobalDataScript.gamePlayPanel.GetComponent <MyMahjongScript>().exitOrDissoliveRoom(); } GlobalDataScript.loginResponseData = JsonMapper.ToObject <AvatarVO>(response.message); ChatSocket.getInstance().sendMsg(new LoginChatRequest(GlobalDataScript.loginResponseData.account.uuid)); panelCreateDialog = Instantiate(Resources.Load("Prefab/Panel_Home")) as GameObject; panelCreateDialog.transform.parent = GlobalDataScript.getInstance().canvsTransfrom; panelCreateDialog.transform.localScale = Vector3.one; panelCreateDialog.GetComponent <RectTransform>().offsetMax = new Vector2(0f, 0f); panelCreateDialog.GetComponent <RectTransform>().offsetMin = new Vector2(0f, 0f); GlobalDataScript.homePanel = panelCreateDialog; removeListener(); Destroy(this); Destroy(gameObject); } }
public Tag Tag(String name, List <Contact> contacts) { if (String.IsNullOrEmpty(name)) { throw new ArgumentNullException(nameof(name)); } if (contacts == null) { throw new ArgumentNullException(nameof(contacts)); } if (!contacts.Any()) { throw new ArgumentException("'users' argument should include more than one user."); } ClientResponse <Tag> result = null; String body = CreateBody(name, false, contacts.ToList <User>()); result = Post <Tag>(body); return(result.Result); }
public virtual void TestClusterSchedulerXML() { WebResource r = Resource(); ClientResponse response = r.Path("ws").Path("v1").Path("cluster").Path("scheduler/" ).Accept(MediaType.ApplicationXml).Get <ClientResponse>(); NUnit.Framework.Assert.AreEqual(MediaType.ApplicationXmlType, response.GetType()); string xml = response.GetEntity <string>(); DocumentBuilderFactory dbf = DocumentBuilderFactory.NewInstance(); DocumentBuilder db = dbf.NewDocumentBuilder(); InputSource @is = new InputSource(); @is.SetCharacterStream(new StringReader(xml)); Document dom = db.Parse(@is); NodeList scheduler = dom.GetElementsByTagName("scheduler"); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, scheduler.GetLength ()); NodeList schedulerInfo = dom.GetElementsByTagName("schedulerInfo"); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, schedulerInfo. GetLength()); VerifyClusterSchedulerXML(schedulerInfo); }
public async Task <ClientResponse> ExecuteGet(string method) { var fullMethod = $"{_baseUrl}/{method}"; if (_parameters.Any()) { fullMethod += "?"; fullMethod = _parameters.Aggregate(fullMethod, (current, parameter) => current + $"{parameter.Key}={parameter.Value}&"); fullMethod = fullMethod.Substring(0, fullMethod.Length - 1); } var response = await _httpClient.GetAsync(fullMethod).ConfigureAwait(false); var data = JsonConvert.DeserializeObject <Dictionary <string, object> >(await response.Content.ReadAsStringAsync().ConfigureAwait(false)); var result = new ClientResponse { Content = data.FirstOrDefault().Value as bool?, Status = response.StatusCode, StatusDescription = response.ReasonPhrase }; return(result); }
public virtual void TestSingleNodesXML() { rm.Start(); WebResource r = Resource(); MockNM nm1 = rm.RegisterNode("h1:1234", 5120); // MockNM nm2 = rm.registerNode("h2:1235", 5121); ClientResponse response = r.Path("ws").Path("v1").Path("cluster").Path("nodes").Path ("h1:1234").Accept(MediaType.ApplicationXml).Get <ClientResponse>(); NUnit.Framework.Assert.AreEqual(MediaType.ApplicationXmlType, response.GetType()); string xml = response.GetEntity <string>(); DocumentBuilderFactory dbf = DocumentBuilderFactory.NewInstance(); DocumentBuilder db = dbf.NewDocumentBuilder(); InputSource @is = new InputSource(); @is.SetCharacterStream(new StringReader(xml)); Document dom = db.Parse(@is); NodeList nodes = dom.GetElementsByTagName("node"); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, nodes.GetLength ()); VerifyNodesXML(nodes, nm1); rm.Stop(); }
/// <exception cref="Org.Codehaus.Jettison.Json.JSONException"/> /// <exception cref="System.Exception"/> public virtual void TestNodeSingleContainersHelper(string media) { WebResource r = Resource(); Org.Apache.Hadoop.Yarn.Server.Nodemanager.Containermanager.Application.Application app = new MockApp(1); nmContext.GetApplications()[app.GetAppId()] = app; Dictionary <string, string> hash = AddAppContainers(app); Org.Apache.Hadoop.Yarn.Server.Nodemanager.Containermanager.Application.Application app2 = new MockApp(2); nmContext.GetApplications()[app2.GetAppId()] = app2; AddAppContainers(app2); foreach (string id in hash.Keys) { ClientResponse response = r.Path("ws").Path("v1").Path("node").Path("containers") .Path(id).Accept(media).Get <ClientResponse>(); NUnit.Framework.Assert.AreEqual(MediaType.ApplicationJsonType, response.GetType() ); JSONObject json = response.GetEntity <JSONObject>(); VerifyNodeContainerInfo(json.GetJSONObject("container"), nmContext.GetContainers( )[ConverterUtils.ToContainerId(id)]); } }
// public void toggleHongClick(){ // // if (zhuanzhuanGameRule [2].isOn) { // zhuanzhuanGameRule [0].isOn = true; // } // } // // public void toggleQiangGangHuClick(){ // if (zhuanzhuanGameRule [1].isOn) { // zhuanzhuanGameRule [2].isOn = false; // } // } public void onCreateRoomCallback(ClientResponse response) { MyDebug.Log(response.message); if (response.status == 1) { //RoomCreateResponseVo responseVO = JsonMapper.ToObject<RoomCreateResponseVo> (response.message); int roomid = Int32.Parse(response.message); sendVo.roomId = roomid; GlobalDataScript.roomVo = sendVo; GlobalDataScript.loginResponseData.roomId = roomid; //GlobalDataScript.loginResponseData.isReady = true; GlobalDataScript.loginResponseData.main = true; GlobalDataScript.loginResponseData.isOnLine = true; //SceneManager.LoadSceneAsync(1); /** * if (gameSence == null) { * gameSence = Instantiate (Resources.Load ("Prefab/Panel_GamePlay")) as GameObject; * gameSence.transform.parent = GlobalDataScript.getInstance ().canvsTransfrom; * gameSence.transform.localScale = Vector3.one; * gameSence.GetComponent<RectTransform> ().offsetMax = new Vector2 (0f, 0f); * gameSence.GetComponent<RectTransform> ().offsetMin = new Vector2 (0f, 0f); * gameSence.GetComponent<MyMahjongScript> ().createRoomAddAvatarVO (GlobalDataScript.loginResponseData); * }*/ GlobalDataScript.gamePlayPanel = PrefabManage.loadPerfab("Prefab/Panel_GamePlay"); GlobalDataScript.gamePlayPanel.GetComponent <MyMahjongScript> ().createRoomAddAvatarVO(GlobalDataScript.loginResponseData); closeDialog(); } else { TipsManagerScript.getInstance().setTips(response.message); } }
// TODO: Verify ClientRequest values. static async Task HandleRealmListTicketRequest(ClientRequest clientRequest, BnetSession session) { var paramIdentityValue = clientRequest.GetVariant("Param_Identity")?.BlobValue.ToStringUtf8(); var paramClientInfoValue = clientRequest.GetVariant("Param_ClientInfo")?.BlobValue.ToStringUtf8(); if (paramIdentityValue != null && paramClientInfoValue != null) { var realmListTicketIdentity = CreateObject <RealmListTicketIdentity>(paramIdentityValue, true); var realmListTicketClientInformation = CreateObject <RealmListTicketClientInformation>(paramClientInfoValue, true); session.GameAccount = session.Account.GameAccounts.SingleOrDefault(ga => ga.Id == realmListTicketIdentity.GameAccountId); if (session.GameAccount != null) { session.RealmListSecret = realmListTicketClientInformation.Info.Secret.Select(x => Convert.ToByte(x)).ToArray(); session.RealmListTicket = new byte[0].GenerateRandomKey(32); var realmListTicketResponse = new ClientResponse(); realmListTicketResponse.Attribute.Add(new Bgs.Protocol.Attribute { Name = "Param_RealmListTicket", Value = new Variant { BlobValue = ByteString.CopyFrom(session.RealmListTicket) } }); await session.Send(realmListTicketResponse); } } else { session.Dispose(); } }
public JsonResult ClientResponse(Func<object> func, string contentType, Encoding encoding, JsonRequestBehavior behavior) { var c = new ClientResponse(func); return Json(c, contentType, encoding, behavior); }
private void onContactInfoResponse(ClientResponse response) { contactInfoContent.text = response.message; contactInfoPanel.SetActive(true); }
/// <summary> /// Validate a client /// <para /> /// Example SQL query: /// <code> /// # Client ID + redirect URI /// SELECT oauth_clients.id, oauth_clients.secret, oauth_client_endpoints.redirect_uri, oauth_clients.name /// FROM oauth_clients LEFT JOIN oauth_client_endpoints ON oauth_client_endpoints.client_id = oauth_clients.id /// WHERE oauth_clients.id = :clientId AND oauth_client_endpoints.redirect_uri = :redirectUri /// <para /> /// # Client ID + client secret /// SELECT oauth_clients.id, oauth_clients.secret, oauth_clients.name FROM oauth_clients WHERE /// oauth_clients.id = :clientId AND oauth_clients.secret = :clientSecret /// <para /> /// # Client ID + client secret + redirect URI /// SELECT oauth_clients.id, oauth_clients.secret, oauth_client_endpoints.redirect_uri, oauth_clients.name FROM /// oauth_clients LEFT JOIN oauth_client_endpoints ON oauth_client_endpoints.client_id = oauth_clients.id /// WHERE oauth_clients.id = :clientId AND oauth_clients.secret = :clientSecret AND /// oauth_client_endpoints.redirect_uri = :redirectUri /// </code> /// <para /> /// Response: /// <code> /// ClientResponse ( /// [client_id] => (string) The client ID /// [client secret] => (string) The client secret /// [redirect_uri] => (string) The redirect URI used in this request /// [name] => (string) The name of the client /// ) /// </code> /// </summary> /// <param name="grantType">The grant type used in the request (default = null)</param> /// <param name="clientId">The client's ID</param> /// <param name="clientSecret">The client's secret (default = null)</param> /// <param name="redirectUri">The client's redirect URI (default = null)</param> /// <returns>Returns null if the validation fails, ClientResponse on success</returns> public ClientResponse GetClient(GrantTypIdentifier grantType, string clientId, string clientSecret = null, string redirectUri = null) { Uri uri = null; if (string.IsNullOrEmpty(clientId)) throw new ArgumentException("clientId"); if (!string.IsNullOrEmpty(redirectUri)) uri = new Uri(redirectUri); ClientResponse response = null; using (var adc = new AditOAUTHDataContext(Constants.DBConnectionString)) { if (!string.IsNullOrEmpty(redirectUri) && string.IsNullOrEmpty(clientSecret)) { if (uri == null) throw new ArgumentException("redirectUri"); // SELECT oauth_clients.id, oauth_clients.secret, oauth_client_endpoints.redirect_uri, oauth_clients.name // FROM oauth_clients // LEFT JOIN oauth_client_endpoints ON oauth_client_endpoints.client_id = oauth_clients.id // WHERE oauth_clients.id = :clientId // AND oauth_client_endpoints.redirect_uri = :redirectUri var client = from oc in adc.oauth_clients join oce in adc.oauth_client_endpoints on oc.id equals oce.client_id into ce from suboc in ce.DefaultIfEmpty() where oc.id == clientId && suboc.uri_protocol == uri.Scheme && suboc.uri_domain == uri.Host && suboc.uri_port == uri.Port select new { oc.id, oc.secret, oc.name, redirect_uri = suboc == null ? string.Empty : suboc.uri_protocol + suboc.uri_domain + (suboc.uri_port.HasValue ? ":" + suboc.uri_port : string.Empty) + suboc.uri_path, oc.auto_approve }; var c = client.SingleOrDefault(); if (c != null) response = new ClientResponse { ClientID = c.id, ClientSecret = c.secret, RedirectUri = c.redirect_uri, Name = c.name, AutoApprove = c.auto_approve }; } else if (!string.IsNullOrEmpty(clientSecret) && string.IsNullOrEmpty(redirectUri)) { // SELECT oauth_clients.id, oauth_clients.secret, oauth_clients.name // FROM oauth_clients // WHERE oauth_clients.id = :clientId // AND oauth_clients.secret = :clientSecret var client = adc.oauth_clients.Where(o => o.id == clientId && o.secret == clientSecret) .Select(o => new { o.id, secrect = o.secret, o.name }) .SingleOrDefault(); if (client != null) response = new ClientResponse { ClientID = client.id, ClientSecret = client.secrect, Name = client.name }; } else if (!string.IsNullOrEmpty(clientSecret) && !string.IsNullOrEmpty(redirectUri)) { // SELECT oauth_clients.id, oauth_clients.secret, oauth_client_endpoints.redirect_uri, oauth_clients.name // FROM oauth_clients // LEFT JOIN oauth_client_endpoints ON oauth_client_endpoints.client_id = oauth_clients.id // WHERE oauth_clients.id = :clientId // AND oauth_clients.secret = :clientSecret // AND oauth_client_endpoints.redirect_uri = :redirectUri var client = from oc in adc.oauth_clients join oce in adc.oauth_client_endpoints on oc.id equals oce.client_id into ce from suboc in ce.DefaultIfEmpty() where oc.id == clientId && oc.secret == clientSecret && suboc.uri_protocol == uri.Scheme && suboc.uri_domain == uri.Host && suboc.uri_port == uri.Port select new { oc.id, oc.secret, oc.name, redirect_uri = suboc == null ? string.Empty : suboc.uri_protocol + suboc.uri_domain + (suboc.uri_port.HasValue ? ":" + suboc.uri_port : string.Empty) + suboc.uri_path, }; var c = client.SingleOrDefault(); if (c != null) response = new ClientResponse { ClientID = c.id, ClientSecret = c.secret, RedirectUri = c.redirect_uri, Name = c.name }; } } return response; }
/// <summary> /// Send an Outcomes 1.0 ReplaceResult request. /// </summary> /// <param name="client">The HttpClient that will be used to process the request.</param> /// <param name="serviceUrl">The URL to send the request to.</param> /// <param name="consumerKey">The OAuth key to sign the request.</param> /// <param name="consumerSecret">The OAuth secret to sign the request.</param> /// <param name="lisResultSourcedId">The LisResult to receive the score.</param> /// <param name="score">The score.</param> /// <returns>A <see cref="ClientResponse"/>.</returns> public static async Task <ClientResponse> ReplaceResultAsync(HttpClient client, string serviceUrl, string consumerKey, string consumerSecret, string lisResultSourcedId, double?score) { try { var imsxEnvelope = new imsx_POXEnvelopeType { imsx_POXHeader = new imsx_POXHeaderType { Item = new imsx_RequestHeaderInfoType() }, imsx_POXBody = new imsx_POXBodyType { Item = new replaceResultRequest() } }; var imsxHeader = (imsx_RequestHeaderInfoType)imsxEnvelope.imsx_POXHeader.Item; imsxHeader.imsx_version = imsx_GWSVersionValueType.V10; imsxHeader.imsx_messageIdentifier = Guid.NewGuid().ToString(); var imsxBody = (replaceResultRequest)imsxEnvelope.imsx_POXBody.Item; imsxBody.resultRecord = new ResultRecordType { sourcedGUID = new SourcedGUIDType { sourcedId = lisResultSourcedId }, result = new ResultType { resultScore = new TextType { language = LtiConstants.ScoreLanguage, // The LTI 1.1 specification states in 6.1.1. that the score in replaceResult should // always be formatted using “en” formatting // (http://www.imsglobal.org/LTI/v1p1p1/ltiIMGv1p1p1.html#_Toc330273034). textString = score?.ToString(new CultureInfo(LtiConstants.ScoreLanguage)) } } }; var outcomeResponse = new ClientResponse(); try { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(LtiConstants.ImsxOutcomeMediaType)); // Create a UTF8 encoding of the request var xml = await GetXmlAsync(imsxEnvelope); var xmlContent = new StringContent(xml, Encoding.UTF8, LtiConstants.ImsxOutcomeMediaType); await SecuredClient.SignRequest(client, HttpMethod.Post, serviceUrl, xmlContent, consumerKey, consumerSecret); // Post the request and check the response using (var response = await client.PostAsync(serviceUrl, xmlContent)) { outcomeResponse.StatusCode = response.StatusCode; if (response.IsSuccessStatusCode) { var imsxResponseEnvelope = (imsx_POXEnvelopeType)ImsxResponseSerializer.Deserialize(await response.Content.ReadAsStreamAsync()); var imsxResponseHeader = (imsx_ResponseHeaderInfoType)imsxResponseEnvelope.imsx_POXHeader.Item; var imsxResponseStatus = imsxResponseHeader.imsx_statusInfo.imsx_codeMajor; outcomeResponse.StatusCode = imsxResponseStatus == imsx_CodeMajorType.success ? HttpStatusCode.OK : HttpStatusCode.BadRequest; } #if DEBUG outcomeResponse.HttpRequest = await response.RequestMessage.ToFormattedRequestStringAsync(new StringContent(xml, Encoding.UTF8, LtiConstants.ImsxOutcomeMediaType)); outcomeResponse.HttpResponse = await response.ToFormattedResponseStringAsync(); #endif } } catch (HttpRequestException ex) { outcomeResponse.Exception = ex; outcomeResponse.StatusCode = HttpStatusCode.BadRequest; } catch (Exception ex) { outcomeResponse.Exception = ex; outcomeResponse.StatusCode = HttpStatusCode.InternalServerError; } return(outcomeResponse); } catch (Exception ex) { return(new ClientResponse { Exception = ex, StatusCode = HttpStatusCode.InternalServerError }); } }
public async Task <IActionResult> SaveInfoSupervisor() { UserModel userSession = HttpContext.Session.Get <UserModel>("UserSesion"); AssignmentModel asign = HttpContext.Session.Get <AssignmentModel>("ReporModelSupervisor"); ReportModel reportModelResult = null; if (asign.Report == null) { reportModelResult = new ReportModel(); } else { reportModelResult = asign.Report; } reportModelResult.NameFile = string.Empty; reportModelResult.FileData = new byte[] { }; try { if (!Request.HasFormContentType) { return(Json(new { content = "Error" })); } if (Request.Form.Files.Count > 0) { if (Request.Form.Files["FileTechnical"] != null) { IFormFile file = Request.Form.Files["FileTechnical"]; byte[] data; using (var br = new BinaryReader(file.OpenReadStream())) data = br.ReadBytes((int)file.OpenReadStream().Length); reportModelResult.AssignmentId = asign.Id; reportModelResult.FileData = data; reportModelResult.ModifiedBy = userSession.Name; reportModelResult.NameFile = file.FileName.Trim(); } } List <FileModel> listFiles = new List <FileModel>(); foreach (var item in reportModelResult.Files) { FileModel newFile = new FileModel(); newFile = item; if (item.Status != 2) { if (item.Status == 1) { newFile.FileData = new byte[] { }; newFile.Name = string.Empty; } listFiles.Insert(0, newFile); } } reportModelResult.AssignmentId = asign.Id; reportModelResult.Comment2 = Request.Form["Comment2"]; string strCheck = Request.Form["Check"]; reportModelResult.ActionType = Convert.ToInt16(Request.Form["action"]); if (strCheck == "on") { reportModelResult.Check = true; } if (reportModelResult.ActionType == 2) { reportModelResult.Sent2 = true; } reportModelResult.Files = listFiles; ClientResponse clientResponse = await _assignmentService.AddOrUpdateSendFileToReportSupervisor(reportModelResult); if (clientResponse == null || clientResponse.Status != System.Net.HttpStatusCode.OK) { return(Json(new { content = "Error" })); } } catch (Exception) { return(Json(new { content = "Error" })); } return(Json(new { content = "Ok" })); }
// TODO: Implement realm join function. static async Task HandleRealmJoinRequest(ClientRequest clientRequest, BnetSession session) { var realmJoinRequest = clientRequest.GetVariant("Command_RealmJoinRequest_v1_b9")?.StringValue; var realmAddress = clientRequest.GetVariant("Param_RealmAddress")?.UintValue; var realmListTicket = clientRequest.GetVariant("Param_RealmListTicket")?.BlobValue.ToByteArray(); var bnetSessionKey = clientRequest.GetVariant("Param_BnetSessionKey")?.BlobValue.ToByteArray(); // Check for valid realmlist ticket. if (realmListTicket.Compare(session.RealmListTicket)) { var realmJoinResponse = new ClientResponse(); await session.Send(realmJoinResponse); } }
public User ConvertToUser(Visitor visitor, User user) { if (visitor == null) { throw new ArgumentNullException(nameof(visitor)); } if (user == null) { throw new ArgumentNullException(nameof(user)); } object userBody = null; if (!String.IsNullOrEmpty(user.id)) { userBody = new { id = user.id } } ; else if (!String.IsNullOrEmpty(user.user_id)) { userBody = new { user_id = user.user_id } } ; else if (!String.IsNullOrEmpty(user.email)) { userBody = new { email = user.email } } ; else { throw new ArgumentException("you need to provide either 'user.id', 'user.user_id', or 'user.email' to convert a visitor."); } object visitorBody = null; if (!String.IsNullOrEmpty(visitor.id)) { visitorBody = new { id = visitor.id } } ; else if (!String.IsNullOrEmpty(visitor.user_id)) { visitorBody = new { user_id = visitor.user_id } } ; else if (!String.IsNullOrEmpty(visitor.email)) { visitorBody = new { email = visitor.email } } ; else { throw new ArgumentException("you need to provide either 'visitor.id', 'visitor.user_id', or 'visitor.email' to convert a visitor."); } var body = new { visitor = visitorBody, user = userBody, type = "user" }; String b = JsonConvert.SerializeObject(body, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); ClientResponse <User> result = null; result = Post <User>(b, resource: VISITORS_RESOURCE + Path.DirectorySeparatorChar + VISITORS_CONVERT); return(result.Result); }
/// <summary> /// Send an Outcomes 1.0 DeleteResult request. /// </summary> /// <param name="client">The HttpClient that will be used to process the request.</param> /// <param name="serviceUrl">The URL to send the request to.</param> /// <param name="consumerKey">The OAuth key to sign the request.</param> /// <param name="consumerSecret">The OAuth secret to sign the request.</param> /// <param name="sourcedId">The LisResultSourcedId to be deleted.</param> /// <returns>A <see cref="ClientResponse"/>.</returns> public static async Task <ClientResponse> DeleteResultAsync(HttpClient client, string serviceUrl, string consumerKey, string consumerSecret, string sourcedId) { try { var imsxEnvelope = new imsx_POXEnvelopeType { imsx_POXHeader = new imsx_POXHeaderType { Item = new imsx_RequestHeaderInfoType() }, imsx_POXBody = new imsx_POXBodyType { Item = new deleteResultRequest() } }; var imsxHeader = (imsx_RequestHeaderInfoType)imsxEnvelope.imsx_POXHeader.Item; imsxHeader.imsx_version = imsx_GWSVersionValueType.V10; imsxHeader.imsx_messageIdentifier = Guid.NewGuid().ToString(); var imsxBody = (deleteResultRequest)imsxEnvelope.imsx_POXBody.Item; imsxBody.resultRecord = new ResultRecordType { sourcedGUID = new SourcedGUIDType { sourcedId = sourcedId } }; var outcomeResponse = new ClientResponse(); try { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(LtiConstants.ImsxOutcomeMediaType)); // Create a UTF8 encoding of the request var xml = await GetXmlAsync(imsxEnvelope); var xmlContent = new StringContent(xml, Encoding.UTF8, LtiConstants.ImsxOutcomeMediaType); await SecuredClient.SignRequest(client, HttpMethod.Post, serviceUrl, xmlContent, consumerKey, consumerSecret); // Post the request and check the response using (var response = await client.PostAsync(serviceUrl, xmlContent)) { outcomeResponse.StatusCode = response.StatusCode; if (response.IsSuccessStatusCode) { var imsxResponseEnvelope = (imsx_POXEnvelopeType)ImsxResponseSerializer.Deserialize(await response.Content.ReadAsStreamAsync()); var imsxResponseHeader = (imsx_ResponseHeaderInfoType)imsxResponseEnvelope.imsx_POXHeader.Item; var imsxResponseStatus = imsxResponseHeader.imsx_statusInfo.imsx_codeMajor; outcomeResponse.StatusCode = imsxResponseStatus == imsx_CodeMajorType.success ? HttpStatusCode.OK : HttpStatusCode.BadRequest; } #if DEBUG outcomeResponse.HttpRequest = await response.RequestMessage.ToFormattedRequestStringAsync(new StringContent(xml, Encoding.UTF8, LtiConstants.ImsxOutcomeMediaType)); outcomeResponse.HttpResponse = await response.ToFormattedResponseStringAsync(); #endif } } catch (HttpRequestException ex) { outcomeResponse.Exception = ex; outcomeResponse.StatusCode = HttpStatusCode.BadRequest; } catch (Exception ex) { outcomeResponse.Exception = ex; outcomeResponse.StatusCode = HttpStatusCode.InternalServerError; } return(outcomeResponse); } catch (Exception ex) { return(new ClientResponse { Exception = ex, StatusCode = HttpStatusCode.InternalServerError }); } }
// TODO: Implement. static Task HandleLastCharPlayedRequest(ClientRequest clientRequest, BnetSession session) { var lastCharPlayedResponse = new ClientResponse(); return session.Send(lastCharPlayedResponse); }
private void RoomBackResponse(ClientResponse response) { if (GlobalDataScript.homePanel != null) { GlobalDataScript.homePanel.GetComponent <HomePanelScript> ().removeListener(); Destroy(GlobalDataScript.homePanel); } GlobalDataScript.reEnterRoomData = JsonMapper.ToObject <RoomCreateVo> (response.message); GlobalDataScript.goldType = GlobalDataScript.reEnterRoomData.goldType; if (GlobalDataScript.gamePlayPanel != null) { if (GlobalDataScript.reEnterRoomData.gameType == (int)GameTypePK.NULL) { GlobalDataScript.gamePlayPanel.GetComponent <MyMahjongScript> ().exitOrDissoliveRoom(); } else if (GlobalDataScript.reEnterRoomData.gameType == (int)GameTypePK.PDK) { GlobalDataScript.gamePlayPanel.GetComponent <MyPDKScript> ().exitOrDissoliveRoom(); } else if (GlobalDataScript.reEnterRoomData.gameType == (int)GameTypePK.DN) { GlobalDataScript.gamePlayPanel.GetComponent <MyDNScript> ().exitOrDissoliveRoom(); } else if (GlobalDataScript.reEnterRoomData.gameType == (int)GameTypePK.DZPK) { GlobalDataScript.gamePlayPanel.GetComponent <MyDZPKScript> ().exitOrDissoliveRoom(); } else if (GlobalDataScript.reEnterRoomData.gameType == (int)GameTypePK.AMH) { GlobalDataScript.gamePlayPanel.GetComponent <MyDZPKScript>().exitOrDissoliveRoom(); } } for (int i = 0; i < GlobalDataScript.reEnterRoomData.playerList.Count; i++) { AvatarVO itemData = GlobalDataScript.reEnterRoomData.playerList [i]; if (itemData.account.openid == GlobalDataScript.loginResponseData.account.openid) { GlobalDataScript.loginResponseData.account.uuid = itemData.account.uuid; GlobalDataScript.loginResponseData.account.roomcard = itemData.account.roomcard; GlobalDataScript.loginResponseData.account.gold = itemData.account.gold; GlobalDataScript.loginResponseData.account.isCheat = itemData.account.isCheat; ChatSocket.getInstance().sendMsg(new LoginChatRequest(GlobalDataScript.loginResponseData.account.uuid)); break; } } if (GlobalDataScript.reEnterRoomData.gameType == (int)GameTypePK.NULL) { GlobalDataScript.gamePlayPanel = PrefabManage.loadPerfab("Prefab/Panel_GamePlay"); } else if (GlobalDataScript.reEnterRoomData.gameType == (int)GameTypePK.PDK) { GlobalDataScript.gamePlayPanel = PrefabManage.loadPerfab("Prefab/Panel_GamePDK"); } else if (GlobalDataScript.reEnterRoomData.gameType == (int)GameTypePK.DN) { GlobalDataScript.gamePlayPanel = PrefabManage.loadPerfab("Prefab/Panel_GameDN"); } else if (GlobalDataScript.reEnterRoomData.gameType == (int)GameTypePK.DZPK) { GlobalDataScript.gamePlayPanel = PrefabManage.loadPerfab("Prefab/Panel_GameDZPK"); } else if (GlobalDataScript.roomVo.gameType == (int)GameTypePK.AMH) { GlobalDataScript.gamePlayPanel = PrefabManage.loadPerfab("Prefab/Panel_GameAMH"); } removeListener(); Destroy(this); Destroy(gameObject); }
// TODO: Implement loading existing realms. // TODO: Implement existing character counts. static async Task HandleRealmListRequest(ClientRequest clientRequest, BnetSession session) { var realmJoinRequest = clientRequest.GetVariant("Command_RealmListRequest_v1_b9")?.StringValue; var realmListTicket = clientRequest.GetVariant("Param_RealmListTicket")?.BlobValue.ToByteArray(); if (session.RealmListTicket.Compare(realmListTicket)) { var realmListResponse = new ClientResponse(); var realmlist = new RealmListUpdates(); realmListResponse.Attribute.Add(new Bgs.Protocol.Attribute { Name = "Param_RealmList", Value = new Variant { BlobValue = ByteString.CopyFrom(Deflate("JSONRealmListUpdates", realmlist)) } }); var realmCharacterCountList = new RealmCharacterCountList(); realmListResponse.Attribute.Add(new Bgs.Protocol.Attribute { Name = "Param_CharacterCountList", Value = new Variant { BlobValue = ByteString.CopyFrom(Deflate("JSONRealmCharacterCountList", realmCharacterCountList)) } }); await session.Send(realmListResponse); } }
//房卡变化处理 private void onCardChangeNotify(ClientResponse response) { cardCountText.text = response.message; GlobalData.getInstance().myAvatarVO.account.roomcard = int.Parse(response.message); }
private void HandleResponse(ClientResponse response) { switch(response) { case ClientResponse.Break: { System.Diagnostics.Debugger.Break(); break; } case ClientResponse.Exit: { Environment.Exit(0); break; } } }