private static void ReceiveRemoteRequest(byte[] bytes) { ModLogger.Info("Received remote request..."); RemoteRequest request = null; try { request = NetworkUtil.DeserializeRequest(bytes); } catch (Exception e) { ModLogger.Error(e.Message); return; } ModLogger.Info("Successfully deserialized RemoteRequest."); if (request.RequestType == RemoteRequestType.WHITELIST_ACTION) { var clientRequest = request as WhitelistActionRequest; if (clientRequest == null) { ModLogger.Error("No serialized data (expected WhitelistActionRequest)!"); return; } ReceiveWhitelist(clientRequest.WhitelistAction, clientRequest.Whitelist); } else { ModLogger.Warning(string.Format("Invalid request type '{0}' to client!", request.RequestType)); } }
public RemoteResponse ExecuteRequest(RemoteRequest request) { RemoteResponse ret; ret = clientServiceContractInstance.ExecuteRequest(request); return(ret); }
public static void SendToClient(ulong recipient, RemoteRequest payload) { var bytes = MyAPIGateway.Utilities.SerializeToBinary(payload); MyAPIGateway.Multiplayer.SendMessageTo(Config.MessageHandlerID, bytes, recipient); //ReceiveRemoteRequest(bytes); }
private static void ReceiveRemoteRequest(byte[] bytes) { RemoteRequest request = null; try { request = NetworkUtil.DeserializeRequest(bytes); } catch (Exception e) { Log.Error(e.Message); return; } if (request.RequestType == RemoteRequestType.CLIENT_REGISTRATION) { SendWhitelistToClient(request.Sender); } else if (request.RequestType == RemoteRequestType.RECOMPILE) { var recompileRequest = request as RecompileRequest; if (recompileRequest == null) { Log.Error("Request Deserialization: No serialized data (expected RecompileRequest)!"); return; } RecompilePB(recompileRequest.PbId, recompileRequest.ScriptId); } else { Log.Warn(string.Format("Invalid request type '{0}' to server!", request.RequestType)); } }
private void PullAcademicData() { try { _consoleInfoData = "Starting Pull of Academic Data"; var settings = RemoteRequest.Get( $"{DatabaseManager.UpdateSpec.RemoteUrl}ApiSettings/PullAcademicData"); if (settings.Result.Status) { DatabaseManager.AcademicSetUpData = Newtonsoft.Json.JsonConvert.DeserializeObject <AcademicSetUpData>( Newtonsoft.Json.JsonConvert.SerializeObject(settings.Result.Data)); _consoleInfoData = $"Pulled Academic Data Successfully"; } else { _consoleInfoData = $"Issue with Synchronization of Academic Data. Please contact the Adminsitrator"; return; } } catch (Exception e) { ErrorHandler.TreatError(e); } }
protected override void ClickProcess() { var index = GlobalVariables.CurrentRobotState.MotionIndex; if (index == 0) { index = GlobalVariables.CurrentListMotion.Count - 1; GlobalVariables.CurrentRobotState.MotionIndex = GlobalVariables.CurrentListMotion.Count - 1; } else { index--; GlobalVariables.CurrentRobotState.MotionIndex--; } if (index < 0 || index >= GlobalVariables.CurrentListMotion.Count) { Request = null; return; } ulong previousMotionID = GlobalVariables.CurrentListMotion[index].MotionID; Console.WriteLine("{0}:{1}", GlobalVariables.CurrentRobotState.MotionIndex, previousMotionID); Request = new RemoteRequest(RobotPacket.PacketID.SelectMotionToPlay, -1, previousMotionID); }
private void PauseRequest() { var pauseRequest = new RemoteRequest(RobotPacket.PacketID.Pause); pauseRequest.ProcessSuccessfully += (data) => { ViewModel.StateButton = PlayPauseButtonModel.ButtonState.Play; Dispatcher.BeginInvoke((Action)GetState); }; pauseRequest.ProcessError += (errorCode, msg) => { Dispatcher.BeginInvoke((Action) delegate { Cursor = Cursors.Arrow; switch (errorCode) { case RobotRequest.ErrorCode.SetupConnection: case RobotRequest.ErrorCode.WrongSessionID: OnUpdateParentControl("MustReconnect"); break; } }); Debug.Fail(msg); }; GlobalVariables.RobotWorker.AddJob(pauseRequest); }
private void UntransformRequest() { var untransformRequest = new RemoteRequest(RobotPacket.PacketID.CloseTransform); untransformRequest.ProcessSuccessfully += (data) => { ViewModel.State = RobotTransformButtonModel.ButtonState.Transform; Dispatcher.BeginInvoke((Action) delegate { Cursor = Cursors.Arrow; OnUpdateParentControl(null); }); }; untransformRequest.ProcessError += (errorCode, msg) => { Dispatcher.BeginInvoke((Action) delegate { Cursor = Cursors.Arrow; switch (errorCode) { case RobotRequest.ErrorCode.SetupConnection: case RobotRequest.ErrorCode.WrongSessionID: OnUpdateParentControl("MustReconnect"); break; } }); Debug.Fail(msg, Enum.GetName(typeof(RobotRequest.ErrorCode), errorCode)); }; GlobalVariables.RobotWorker.AddJob(untransformRequest); }
private void Play(ulong motionID) { //if (GlobalVariables.CurrentRobotState.TransformState != RobotState.TransformStates.Opened) //{ // string msgTransform = string.Empty; // string titleTransform = string.Empty; // switch (GlobalVariables.CurrentRobotState.TransformState) // { // case RobotState.TransformStates.Closed: // msgTransform = (string)TryFindResource("MustTransformToPlayText"); // titleTransform = (string)TryFindResource("PleaseTransformText"); // break; // case RobotState.TransformStates.Openning: // case RobotState.TransformStates.Closing: // msgTransform = (string)TryFindResource("RobotTransformingText"); // titleTransform = (string)TryFindResource("WaitToTransformedText"); // break; // } // WPFMessageBox.Show(StaticMainWindow.Window, titleTransform, // msgTransform, MessageBoxButton.OK, // MessageBoxImage.Information, MessageBoxResult.OK); // RemoteListBox.SelectedIndex = -1; // return; //} Cursor = Cursors.Wait; var playRequest = new RemoteRequest(RobotPacket.PacketID.SelectMotionToPlay, -1, motionID); playRequest.ProcessSuccessfully += (data) => Dispatcher.BeginInvoke((Action)(() => GetState(NullMethod, 0))); playRequest.ProcessError += (errorCode, msg) => { Dispatcher.BeginInvoke((Action) delegate { Cursor = Cursors.Arrow; switch (errorCode) { case RobotRequest.ErrorCode.SetupConnection: case RobotRequest.ErrorCode.WrongSessionID: var result = WPFMessageBox.Show(StaticMainWindow.Window, "Your connection to robot is lost", "Do you want to reconnect", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes); if (result == MessageBoxResult.Yes) { ConnectMrobo(); } else { GlobalVariables.RoboOnline = false; UnconnectedTextBox.Visibility = Visibility.Visible; } break; } }); Debug.Fail(msg); }; GlobalVariables.RobotWorker.AddJob(playRequest); }
protected override void ClickProcess() { var stopRequest = new RemoteRequest(RobotPacket.PacketID.Stop); stopRequest.ProcessSuccessfully += (data) => { }; stopRequest.ProcessError += (data, msg) => Debug.Fail(msg); GlobalVariables.RobotWorker.AddJob(stopRequest); }
public async Task <RemoteResponse> Execute(RemoteRequest request, string routingKey) { var awaiter = this._awaitersRegistry.Register(); request.Headers.CorrelationId = awaiter.CorrelationId; request.Headers.RoutingKey = routingKey; request.Headers.ReplyTo = ""; //TODO do we need it here? _sender.Send(request); var response = await awaiter.Result; return(response); }
private void ReceiveMessage(RemoteRequest rr) { if ((rr.TransferObject) is Gateways) { MessageBox.Show("dd"); } }
private void DeleteMotionInRobot(ulong motionID) { var delRequest = new RemoteRequest(RobotPacket.PacketID.DeleteMotion, -1, motionID); delRequest.ProcessSuccessfully += (reply) => Dispatcher.BeginInvoke((Action) delegate { GetListMotion(); RemoteListBox.SelectedIndex = 0; }); delRequest.ProcessError += (errorCode, msg) => Debug.Fail(errorCode.ToString(), msg); GlobalVariables.RobotWorker.AddJob(delRequest); }
private void UpdateVolume(int value) { var volumeRequest = new RemoteRequest(RobotPacket.PacketID.SetVolumeLevel, value); volumeRequest.ProcessSuccessfully += (reply) => Dispatcher.BeginInvoke((Action)UpdateRemoteControl); volumeRequest.ProcessError += (reply, msg) => { if (reply == null) { Debug.Fail(msg); } Debug.Fail(reply.ToString(), msg); }; GlobalVariables.StoreWorker.AddRequest(volumeRequest); }
public static void Broadcast(RemoteRequest payload) { var bytes = MyAPIGateway.Utilities.SerializeToBinary(payload); var players = new List <IMyPlayer>(); MyAPIGateway.Players.GetPlayers(players); foreach (var player in players) { var id = player.SteamUserId; if (id != MyAPIGateway.Multiplayer.MyId && id != MyAPIGateway.Multiplayer.ServerId) { NetworkUtil.SendToClient(id, payload); } } }
private void btnStudentRequest_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(txtStudentMatric.Text.Trim())) { WarnNotify("Warning|Please enter a Matric Number"); return; } new Thread(() => { try { _workingState = true; InfoNotify("Please Wait!|Searching for the Student."); var settings = RemoteRequest.Get( $"{DatabaseManager.UpdateSpec.RemoteUrl}ApiStudentManagement/PullStudentDataByMatricNumber?matricNumber={txtStudentMatric.Text.Trim()}"); if (settings.Result.Status) { _studentData = JsonConvert.DeserializeObject <StudentCompleteData>( JsonConvert.SerializeObject(settings.Result.Data)); if (string.IsNullOrEmpty(_studentData.StudentProfileData.TagId)) { WarnNotify("Awesome!|This is a valid student but it does not have a Tag Yet."); } else { SuccessNotify($"Awesome!|The Tag is Valid. Tag Id is {_tagUID} and Matriculation Number is {_studentData.StudentProfileData.MatricNumber}"); } } else { WarnNotify("Oops!|" + settings.Result.Message); } _workingState = false; } catch (Exception exception) { ErrorHandler.TreatError(exception); } }).Start(); }
private void ConnectMrobo(bool reconnect = false) { //Cursor = Cursors.Wait; var helloRequest = new RemoteRequest(RobotPacket.PacketID.Hello); helloRequest.ProcessSuccessfully += (data) => { Dispatcher.BeginInvoke((Action) delegate { if (!reconnect) { var title = (string)TryFindResource("ConnectToRobotSuccesfullyText"); WPFMessageBox.Show(StaticMainWindow.Window, "", title, MessageBoxButton.OK, MessageBoxImage.Information, MessageBoxResult.OK); } UnconnectedTextBox.Visibility = Visibility.Hidden; //Cursor = Cursors.Arrow; //TransformButton.ViewModel.State = RobotTransformButtonModel.ButtonState.Transform; GetListMotion(); GetState(); //GetState(NullMethod, 0); }); GlobalVariables.RoboOnline = true; }; helloRequest.ProcessError += (errorCode, msg) => { Debug.Fail(msg, Enum.GetName((typeof(RobotRequest.ErrorCode)), errorCode)); Dispatcher.BeginInvoke((Action) delegate { if (!reconnect) { var titleError = (string)TryFindResource("ConnectToRobotErrorText"); var msgError = (string)TryFindResource("CheckDefaultErrorText"); WPFMessageBox.Show(StaticMainWindow.Window, msgError, titleError, MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK); } UnconnectedTextBox.Visibility = Visibility.Visible; Cursor = Cursors.Arrow; }); }; GlobalVariables.RobotWorker.AddJob(helloRequest); }
private bool RemoteTagClean() { try { var settings = RemoteRequest.Get( $"{DatabaseManager.UpdateSpec.RemoteUrl}ApiStudentManagement/UnTagStudent?tagId={_tagUID}"); MessageBox.Show(settings.Result.Message); return(true); } catch (Exception e) { ErrorHandler.TreatError(e); MessageBox.Show(@"Can not Format the Tag at the moment. Cant seem to reach the Server"); return(false); } }
protected override dynamic Invoke(MethodInfo method, object[] args) { if (!typeof(Task).IsAssignableFrom(method.ReturnType)) { throw new InvalidOperationException("ServiceProxy supports only asynchronous methods."); } if (!method.ReturnType.IsGenericType) { throw new InvalidOperationException("ServiceProxy doesn't support VOID methods."); } var request = new RemoteRequest(method.Name, args.Select(JsonConvert.SerializeObject).ToArray()); var routingKey = GetRoutingKey(method.Name); var response = this._executor.Execute(request, routingKey).Result; var convertedResponse = this._converter.Convert(response, method.ReturnType.GetGenericArguments().First()); return(convertedResponse); }
private bool HandleRequest(RemoteRequest request) { _logger.Debug("{ServiceName}: Handling {RequestName}", typeof(TImplementation).Name, request.MethodName); try { var response = this.GetResponse(request.MethodName, request.Args); this.SendResponse(response, request.Headers); } catch (TargetInvocationException e) when(e.InnerException is AggregateException) { this.SendErrorResponse(((AggregateException)e.InnerException).InnerExceptions.First(), request.Headers); } catch (Exception e) { _logger.Error(e, "Sad thing occured"); return(false); } return(true); }
private void MotionTitleItem_DeleteMotion(ulong motionID) { if (GlobalVariables.CurrentRobotState.MusicState == RobotState.MusicStates.MusicPlaying) { var titleStop = (string)TryFindResource("StopDanceToDeleteText"); var msgStop = (string)TryFindResource("WantToStopDanceText"); var result = WPFMessageBox.Show(StaticMainWindow.Window, msgStop, titleStop, MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes); if (result == MessageBoxResult.Yes) { var musicStopRequest = new RemoteRequest(RobotPacket.PacketID.Stop); musicStopRequest.ProcessSuccessfully += (data) => Dispatcher.BeginInvoke((Action)(() => DeleteMotionInRobot(motionID))); musicStopRequest.ProcessError += (data, msg) => Debug.Fail(msg); GlobalVariables.RobotWorker.AddJob(musicStopRequest); } } else { DeleteMotionInRobot(motionID); } }
public RemoteResponse ExecuteRequest(RemoteRequest oRequest) { RemoteResponse ret = null; try { try { ret = base.Channel.ExecuteRequest(oRequest); } catch (FaultException <ExceptionDetail> ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); // extract & throw original exception from Fault contract Exception originalException = null; try { originalException = (Exception)Activator.CreateInstance(Type.GetType(ex.Detail.Type), BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, new object[] { ex.Message, ex }, null); } catch { throw; } throw originalException; } } catch (CommunicationObjectFaultedException ex) { // wrap WCF specific exception throw new RemoteSideFaultedException(ex.Message, ex); } catch (EndpointNotFoundException ex) { // wrap WCF specific exception throw new RemoteSideUnreachableException(ex.Message, ex); } return(ret); }
private void PlayRequest() { RobotState state = GlobalVariables.CurrentRobotState; RemoteRequest playRequest = null; if (state.MusicState == RobotState.MusicStates.MusicIdled) { playRequest = state.MotionID > 2 ? new RemoteRequest(RobotPacket.PacketID.SelectMotionToPlay, -1, state.MotionID) : new RemoteRequest(RobotPacket.PacketID.SelectMotionToPlay, -1, GlobalVariables.CurrentListMotion[0].MotionID); } else { playRequest = new RemoteRequest(RobotPacket.PacketID.Play); } playRequest.ProcessSuccessfully += (data) => { ViewModel.StateButton = PlayPauseButtonModel.ButtonState.Pause; Dispatcher.BeginInvoke((Action)GetState); }; playRequest.ProcessError += (errorCode, msg) => { Dispatcher.BeginInvoke((Action) delegate { Cursor = Cursors.Arrow; switch (errorCode) { case RobotRequest.ErrorCode.SetupConnection: case RobotRequest.ErrorCode.WrongSessionID: OnUpdateParentControl("MustReconnect"); break; } }); Debug.Fail(msg, Enum.GetName(typeof(RobotRequest.ErrorCode), errorCode)); }; GlobalVariables.RobotWorker.AddJob(playRequest); }
// (client only) public static void SendToServer(RemoteRequest payload) { var bytes = MyAPIGateway.Utilities.SerializeToBinary(payload); MyAPIGateway.Multiplayer.SendMessageToServer(Config.MessageHandlerID, bytes); }
private void PullStudents() { try { var listOfProfileData = new List <List <Data.Student_ProfileData> >(); var listOfAcademicData = new List <List <Student_RegistrationData> >(); var done = 0; _consoleInfoData = "Starting Pull of Student Data"; while (true) { var settings = RemoteRequest.Get( $"{DatabaseManager.UpdateSpec.RemoteUrl}ApiStudentManagement/PullStudentsCompleteData?done={done}"); if (settings.Result.Status) { var batch = Newtonsoft.Json.JsonConvert.DeserializeObject <List <StudentCompleteData> >( Newtonsoft.Json.JsonConvert.SerializeObject(settings.Result.Data)); if (!batch.Any()) { break; } listOfProfileData.Add(batch.Select(x => x.StudentProfileData).ToList()); listOfAcademicData.Add(batch .Select(x => x.StudentData.FirstOrDefault()?.StudentRegistrationData).ToList()); done += batch.Count; _consoleInfoData = $"Pulled Student Batch of {batch.Count}. Total Pulled is {done}"; } else { _consoleInfoData = $"Issue with Synchronization of Student Data. Please contact the Adminsitrator"; return; } } if (listOfProfileData.Any()) { _consoleInfoData = @"Discarding all Previous Records"; DatabaseManager.ExecuteScripts("truncate table dbo.Student_ProfileData"); using (var data = new LocalEntities()) { _consoleInfoData = @" Persisting Student Profile Data"; foreach (var list in listOfProfileData) { _consoleInfoData = @"Processing ..."; data.Student_ProfileData.AddRange(list.Select(innerList => new Student_ProfileData() { MatricNumber = innerList.MatricNumber, TagId = innerList.TagId, IsDeleted = false, Phone = innerList.Phone, FirstName = innerList.FirstName, Email = innerList.Email, LastName = innerList.LastName, Sex = innerList.Sex, Picture = innerList.Picture, BloodGroup = innerList.BloodGroup ?? "", PictureEncoded = string.IsNullOrEmpty(innerList.Picture) ? null : Convert.FromBase64String(innerList.Picture), StudentProfileData = Newtonsoft.Json.JsonConvert.SerializeObject(innerList), RemoteId = innerList.Id })); data.SaveChanges(); } _consoleInfoData = @"Student Profile Data Persistence Successful"; _consoleInfoData = @"Persisting Student Academic Data"; foreach (var acadBatch in listOfAcademicData) { _consoleInfoData = @"Processing ..."; foreach (var acad in acadBatch) { var profile = data.Student_ProfileData.FirstOrDefault(x => x.RemoteId == acad.StudentId); if (profile == null) { continue; } var school = DatabaseManager.AcademicSetUpData.AcademicSetUpDatum.FirstOrDefault(x => x.SchoolSubSchool.Id == acad.SubSchoolId); if (school == null) { continue; } profile.Program = school.SchoolSubSchool.SubSchoolName; profile.Department = school.SchoolSubSchoolDepartment .FirstOrDefault(x => x.Id == acad.SubSchoolDepartmentId)?.SubSchoolDepartmentName; data.Entry(profile).State = EntityState.Modified; } data.SaveChanges(); } _consoleInfoData = @"Student Academic Data Persistence Successful"; } _consoleInfoData = @"Completed Pull of Student Data"; } else { _consoleInfoData = @"No Records found at this time."; } } catch (Exception e) { ErrorHandler.TreatError(e); } }
public object Invoke(string host, string service, string methodName, object[] parameters, Type[] parametersTypes, Type retType) { var endpoint = this._endpointRegistry.GetEndpoint(host); var serializedArs = this._serializationStrategy.SerializeParameters(parameters, parametersTypes); var serializedPInfo = this._serializationStrategy.SerializeParameterTypes(parametersTypes); var requestMessage = new RequestMessage(service, methodName, serializedArs, serializedPInfo); var request = new RemoteRequest(this._context, endpoint, requestMessage, this._serializationStrategy) { ReqPoll = this._requestPoll }; var watch = System.Diagnostics.Stopwatch.StartNew(); if (Castle.Zmq.LogAdapter.LogEnabled) { Castle.Zmq.LogAdapter.LogDebug( "Castle.Facilities.Zmq.Rpc.RemoteRequestService", "About to send request for " + host + "-" + service + "-" + methodName); } var attempts = 0; const int maxAttempts = 3; ResponseMessage response = null; while (attempts++ < maxAttempts) { // request.Monitor = attempts > 1; response = request.Get(); watch.Stop(); if (Castle.Zmq.LogAdapter.LogEnabled) { Castle.Zmq.LogAdapter.LogDebug( "Castle.Facilities.Zmq.Rpc.RemoteRequestService", "Reply from " + host + "-" + service + "-" + methodName + " took " + watch.ElapsedMilliseconds + "ms (" + watch.Elapsed.TotalSeconds + "s). " + "Exception? " + (response.ExceptionInfo != null)); } if (response.ExceptionInfo != null) { if (response.ExceptionInfo.Typename == RemoteRequest.TimeoutTypename) { // our side (local) set a exception info just to inform us - the caller - about a timeout. // since that's the case, attempt to try again continue; } // otherwise -- it's some other kind of error, and we should just fail fast ThrowWithExceptionInfoData(response); } // all went fine if (retType != typeof(void)) { return _serializationStrategy.DeserializeResponseValue(response, retType); } return null; } if (response.ExceptionInfo != null) { ThrowWithExceptionInfoData(response); } return null; }
private void btnAttach_Click(object sender, EventArgs e) { try { if (txtStudentMatric.Text.Trim() != _studentData.StudentProfileData.MatricNumber) { MessageBox.Show( @"Please request for the Student you wish to Tag. Some modifications have been made to the information retrieved."); return; } if (_tag == null) { MessageBox.Show( @"Lets start over. Close this message and Place a blank Tag"); return; } if (!CheckTagValidity()) { var dialogResult = MessageBox.Show( @"The Current Tag has some data on it? This operation will totally overwrite it. Should I proceed?", @"Waiting for Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dialogResult != DialogResult.Yes) { return; } } if (!RemoteTagClean()) { return; } var settings = RemoteRequest.Get( $"{DatabaseManager.UpdateSpec.RemoteUrl}ApiStudentManagement/TagStudent?matricNumber={txtStudentMatric.Text.Trim()}&tagId={_tagUID}"); if (!settings.Result.Status) { MessageBox.Show( @"Cannot Write Tag at the moment. Why? " + settings.Result.Message); return; } var smartPoster = new RtdSmartPoster(); smartPoster.Title.Add(new RtdText(_studentData.StudentProfileData.MatricNumber, "US")); Ndef ndefData = smartPoster; using (var localEntities = new LocalEntities()) { var recordInDb = localEntities.Student_ProfileData.FirstOrDefault(x => x.MatricNumber == txtStudentMatric.Text.Trim()); if (recordInDb != null) { recordInDb.TagId = _tagUID; localEntities.Entry(recordInDb).State = EntityState.Modified; localEntities.SaveChanges(); } } _tag.Content.Clear(); _tag.Content.Add(ndefData); _cardthread = new Thread(() => { card_write_proc(_tag); }); _cardthread.Start(); } catch (Exception exception) { ErrorHandler.TreatError(exception); } }
public Task Send(IMessage message, RemoteAddress to) { try { ThrowIfDisposed(); if (message == null) { throw new ArgumentNullException(nameof(message)); } if (to == null) { throw new ArgumentNullException(nameof(to)); } var client = GetClient(to.EndPoint); if (client == null) { throw new Exception(RpcErrors.CannotResolveEndPoint); } if (!(message is IFutureMessage future)) { try { client.Send(new RemoteMessage(message, to.Actor, WireMessageId.Next())); } catch (Exception e) { return(Task.FromException(e)); } return(Completed); } var request = (RemoteRequest)null; try { request = new RemoteRequest(future, to.Actor, RequestTimedOut); _responseList[request.MessageId] = request; client.Send(request); } catch (Exception e) { future.RespondWithError(e); if (request != null) { AsyncEventPool.Run(request.Dispose); } } return(future.Task); } catch (Exception e) { if (e is SocketException) { CancelWaitingResponses(); } return(Task.FromException(e)); } }
private void btnUpdateSettingsConfirm_Click(object sender, EventArgs e) { try { new Thread(() => { _workingState = true; var settings = RemoteRequest.Get($"{txtUrl.Text.Trim()}apisettings/PullSettings"); if (settings.Result.Status) { var settingData = Newtonsoft.Json.JsonConvert.DeserializeObject <List <System_Setting> >(settings.Result.Data.ToString()); var localEntities = new LocalEntities(); if (!settingData.Any()) { MessageBox.Show(@"No Settings were found on the server"); _workingState = false; return; } DatabaseManager.ExecuteScripts("truncate table dbo.SystemSetting"); localEntities.System_Setting.AddRange(settingData.Select(sd => new System_Setting() { IsDeleted = false, SettingDate = DateTime.Now, SettingKey = sd.SettingKey, SettingValue = sd.SettingValue })); localEntities.SaveChanges(); DatabaseManager.UpdateSpec = new UpdateSpec() { DatabaseFiles = DatabaseManager.UpdateSpec.DatabaseFiles, DatabaseSchema = DatabaseManager.UpdateSpec.DatabaseSchema, RemoteUrl = settingData.FirstOrDefault(x => x.SettingKey == (int)SettingKey.RemoteApi) ?.SettingValue ?? "" }; } else { MessageBox.Show(@"The server cannot be reached at the moment. Please try again later!"); } settings = RemoteRequest.Get($"{txtUrl.Text.Trim()}ApiUserManagement/Pullusers"); if (settings.Result.Status) { DatabaseManager.LocalAuthData = Newtonsoft.Json.JsonConvert.DeserializeObject <List <AuthModel> >( Newtonsoft.Json.JsonConvert.SerializeObject(settings.Result.Data)); var x = DatabaseManager.LocalAuthData; } else { MessageBox.Show(@"The server cannot be reached at the moment. Please try again later!"); } _workingState = false; }).Start(); } catch (Exception exception) { ErrorHandler.TreatError(exception); } }
// This method raises the CopyMotion event private void TransferButton_Click(object sender, RoutedEventArgs e) { if (!GlobalVariables.RoboOnline) { var title = string.Format("{0}!", TryFindResource("ConnectToRobotText")); WPFMessageBox.Show(StaticMainWindow.Window, "", title, MessageBoxButton.OK, MessageBoxImage.Warning, MessageBoxResult.OK); } else { if (CheckExistInRobot(GlobalVariables.CurrentListMotion, MotionID)) { var titleRecopy = (string)TryFindResource("ExistInRobotText"); var msgRecopy = (string)TryFindResource("WantRecopyMotionText"); var recopyResult = WPFMessageBox.Show(StaticMainWindow.Window, msgRecopy, titleRecopy, MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No); if (recopyResult == MessageBoxResult.No) { return; } } if (GlobalVariables.CurrentRobotState.MusicState == RobotState.MusicStates.MusicPlaying) { var titleStop = (string)TryFindResource("StopDanceToCopyText"); var msgStop = (string)TryFindResource("WantToStopDanceText"); var result = WPFMessageBox.Show(StaticMainWindow.Window, msgStop, titleStop, MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes); if (result == MessageBoxResult.Yes) { var musicStopRequest = new RemoteRequest(RobotPacket.PacketID.Stop); musicStopRequest.ProcessSuccessfully += (data) => { Dispatcher.BeginInvoke((Action) delegate { var transferRequest = new TransferMotionToRobot(MotionID); var transferWindow = new Windows.TransferWindow(transferRequest, MotionID.ToString()); if (transferWindow.ShowDialog(StaticMainWindow.Window) == true) { var newEventArgs = new RoutedEventArgs(CopyMotionEvent); RaiseEvent(newEventArgs); } }); }; musicStopRequest.ProcessError += (data, msg) => Debug.Fail(msg); GlobalVariables.RobotWorker.AddJob(musicStopRequest); } } else { var transferRequest = new TransferMotionToRobot(MotionID); var transferWindow = new Windows.TransferWindow(transferRequest, MotionID.ToString()); if (transferWindow.ShowDialog(StaticMainWindow.Window) == true) { var newEventArgs = new RoutedEventArgs(CopyMotionEvent); RaiseEvent(newEventArgs); } } } }
public object Invoke(string host, string service, string methodName, object[] parameters, Type[] parametersTypes, Type retType) { var endpoint = this._endpointRegistry.GetEndpoint(host); var serializedArs = this._serializationStrategy.SerializeParameters(parameters, parametersTypes); var serializedPInfo = this._serializationStrategy.SerializeParameterTypes(parametersTypes); var requestMessage = new RequestMessage(service, methodName, serializedArs, serializedPInfo); var request = new RemoteRequest(this._context, endpoint, requestMessage, this._serializationStrategy) { ReqPoll = this._requestPoll }; var watch = System.Diagnostics.Stopwatch.StartNew(); if (Castle.Zmq.LogAdapter.LogEnabled) { Castle.Zmq.LogAdapter.LogDebug( "Castle.Facilities.Zmq.Rpc.RemoteRequestService", "About to send request for " + host + "-" + service + "-" + methodName); } var attempts = 0; const int maxAttempts = 3; ResponseMessage response = null; while (attempts++ < maxAttempts) { // request.Monitor = attempts > 1; response = request.Get(); watch.Stop(); if (Castle.Zmq.LogAdapter.LogEnabled) { Castle.Zmq.LogAdapter.LogDebug( "Castle.Facilities.Zmq.Rpc.RemoteRequestService", "Reply from " + host + "-" + service + "-" + methodName + " took " + watch.ElapsedMilliseconds + "ms (" + watch.Elapsed.TotalSeconds + "s). " + "Exception? " + (response.ExceptionInfo != null)); } if (response.ExceptionInfo != null) { if (response.ExceptionInfo.Typename == RemoteRequest.TimeoutTypename) { // our side (local) set a exception info just to inform us - the caller - about a timeout. // since that's the case, attempt to try again continue; } // otherwise -- it's some other kind of error, and we should just fail fast ThrowWithExceptionInfoData(response); } // all went fine if (retType != typeof(void)) { return(_serializationStrategy.DeserializeResponseValue(response, retType)); } return(null); } if (response.ExceptionInfo != null) { ThrowWithExceptionInfoData(response); } return(null); }