/// <summary> /// 发送到服务 /// </summary> /// <param name="msg"></param> public void SendMessage(MSMQEntity msmqEntity) { try { if (msmqEntity == null) { return; } MessageQueue MQueue; if (!MessageQueue.Exists(ConstValue.MSMQPathToService)) { return; } MQueue = new MessageQueue(ConstValue.MSMQPathToService); Message Msg = new Message(); Msg.Body = msmqEntity;// JsonConvert.SerializeObject(msmqEntity); Msg.Formatter = new BinaryMessageFormatter(); MQueue.Send(Msg); } catch (Exception ex) { logger.ErrorException("SendMessage", ex); } }
public void ProcessRequest(HttpContext context) { if (IsDebugEnabled) { log.Debug("FusionChart 정보를 Image로 Export 요청을 받았습니다. Request=[{0}]", context.Request.RawUrl); } try { CurrentContext = context; Request = context.Request; Response = context.Response; // Exporting 되는 파일의 경로 ExporterPath = Path.Combine(WebTool.AppPath, SAVE_PATH); ExportChart(); } catch (Exception ex) { if (log.IsErrorEnabled) { log.ErrorException("Fusion Chart를 Exporting 하는데 실패했습니다. Request=" + context.Request.RawUrl, ex); } throw; } if (IsDebugEnabled) { log.Debug("Fusion Chart 정보를 Image로 Export 했습니다. Request=" + context.Request.RawUrl); } // Response.End(); }
public List <UserDTO> GetAllUsers() { List <UserDTO> usersDTO = new List <UserDTO>(); try { List <User> usersResult = _directoryService.GetAllUsers(); foreach (User user in usersResult) { usersDTO.Add(new UserDTO() { FirstName = user.FirstName, LastName = user.LastName, Email = user.EmailAddress, PID = user.PayId.Identity }); } } catch (Exception ex) { _logger.ErrorException("Unable to get list of users from AD", ex); } _logger.Trace(LoggerHelper.ExecutedFunctionMessage(usersDTO)); return(usersDTO); }
public void ProcessRequest(HttpContext context) { if (IsDebugEnabled) { log.Debug("Fusion Chart 정보를 Image로 Export 요청을 받았습니다. Request=" + context.Request); } try { Request = context.Request; Response = context.Response; // Exporting 되는 파일의 경로 ExporterPath = WebTool.AppPath + "/chartExports/"; ExportChart(); } catch (Exception ex) { if (log.IsErrorEnabled) { log.ErrorException("Fusion Chart를 Exporting 하는데 실패했습니다.", ex); } throw; } if (IsDebugEnabled) { log.Debug("Fusion Chart 정보를 Image로 Export 했습니다."); } }
/// <summary> /// 엔티티를 로드하고, UI Control에 바인딩 합니다. /// </summary> /// <param name="exceptionAction">예외발생 시 수행할 Action</param> protected virtual void LoadAndBindEntity(Action <Exception> exceptionAction) { if (IsDebugEnabled) { log.Debug(@"==>S 엔티티[{0}] 목록을 로드하여, TreeView에 바인딩 시킵니다...", ConcreteType.Name); } try { LoadEntity(); BindEntity(); } catch (Exception ex) { var errorMsg = string.Format(@"엔티티[{0}]를 로드하고, Binding 시에 예외가 발생했습니다.", ConcreteType.Name); if (log.IsErrorEnabled) { log.ErrorException(errorMsg, ex); } if (exceptionAction != null) { exceptionAction(ex); } else { WebAppTool.MessageBox(errorMsg, this); } } }
/// <summary> /// Stored Procedure를 수행하고, OUTPUT, RETURN_VALUE를 반환한다. /// </summary> /// <param name="request">요청 항목</param> /// <param name="responseDocument">응답 정보</param> protected virtual void ExecuteProcedure(XdsRequestItem request, XdsResponseDocument responseDocument) { if (IsDebugEnabled) { log.Debug("프로시저를 실행합니다... requestId=[{0}], procedure=[{1}], requestType=[{2}], responseType=[{3}]", request.Id, request.Query, request.RequestKind, request.ResponseKind); } try { var maxSequence = Math.Max(1, request.Values.Count); for (var seqId = 0; seqId < maxSequence; seqId++) { var adoParameters = PrepareParameters(request, seqId).ToArray(); using (var cmd = Ado.GetProcedureCommand(request.Query)) { Ado.ExecuteNonQuery(cmd, adoParameters); var response = responseDocument.AddResponseItem(XmlDataResponseKind.Scalar, request.Id, seqId); ExtractParameters(AdoTool.GetOutputParameters(Ado.Db, cmd), response, seqId); } } } catch (Exception ex) { if (log.IsErrorEnabled) { log.ErrorException(string.Format("프로시저 실행에 실패했습니다. procedure=[{0}]", request.Query), ex); } throw; } if (IsDebugEnabled) { log.Debug("프로시저 실행에 성공했습니다. procedure=[{0}]", request.Query); } }
/// <summary> /// 1. 직렬화된 정보를 <see cref="RequestSerializer"/>를 이용하여, 역직렬화를 수행. <see cref="XdsRequestDocument"/>를 빌드<br/> /// 2. 요청정보를 <see cref="XmlDataManager"/>에 전달하여, 실행 후, 응답정보를 반환 받음<br/> /// 3. 응답정보를 <see cref="ResponseSerializer"/>를 통해 직렬화하여 byte[] 로 반환함. /// </summary> /// <param name="requestBytes">직렬화된 요청 Data</param> /// <returns>응답정보를 직렬화한 byte[]</returns> public virtual byte[] Execute(byte[] requestBytes) { if (IsDebugEnabled) { log.Debug("XML 포맷 방식의 정보를 처리를 시작합니다... IXmlDataManager=[{0}]", XmlDataManager); } requestBytes.ShouldNotBeNull("requestBytes"); try { var requestMsg = RequestSerializer.Deserialize(requestBytes); var XdsResponseDocument = XmlDataManager.Execute(requestMsg); var responseBytes = ResponseSerializer.Serialize(XdsResponseDocument); if (IsDebugEnabled) { log.Debug("요청을 모두 처리하고, 응답 정보를 포맷으로 반환합니다!!!"); } return(responseBytes); } catch (Exception ex) { if (log.IsErrorEnabled) { log.ErrorException("요청 처리 중 예외가 발생했습니다.", ex); } return(ResponseSerializer.Serialize(XmlDataTool.CreateResponseWithError(ex))); } }
/// <summary> /// 1. 직렬화된 정보를 <see cref="IDataServiceAdapter.RequestSerializer"/>를 이용하여, 역직렬화를 수행. <see cref="RequestMessage"/>를 빌드<br/> /// 2. 요청정보를 <see cref="IDataServiceAdapter.DataService"/>에 전달하여, 실행 후, 응답정보를 반환 받음<br/> /// 3. 응답정보를 <see cref="IDataServiceAdapter.ResponseSerializer"/>를 통해 직렬화하여 byte[] 로 반환함. /// </summary> /// <param name="requestBytes">직렬화된 요청 Data</param> /// <returns>응답정보를 직렬화한 byte[]</returns> public virtual byte[] Execute(byte[] requestBytes) { if (IsDebugEnabled) { log.Debug("JSON 포맷 방식의 정보를 처리를 시작합니다... IDataService=[{0}]", DataService); } requestBytes.ShouldNotBeNull("requestBytes"); try { var requestMsg = RequestSerializer.Deserialize(requestBytes); var responseMessage = DataService.Execute(requestMsg); var responseBytes = ResponseSerializer.Serialize(responseMessage); if (IsDebugEnabled) { log.Debug("요청을 모두 처리하고, 응답 정보를 포맷으로 반환합니다!!!"); } return(responseBytes); } catch (Exception ex) { if (log.IsErrorEnabled) { log.ErrorException("요청 처리 중 예외가 발생했습니다.", ex); } return(ResponseSerializer.Serialize(DataServiceTool.CreateResponseMessageWithException(ex))); } }
public List <AdminDTO> GetAllAdminUsers() { try { List <AdminDTO> adminsDTO = new List <AdminDTO>(); List <Admin> admins = _adminRepository.GetAll(); admins.ForEach(a => adminsDTO.Add(new AdminDTO() { ID = a.ID, PID = a.PID, FirstName = a.FirstName, LastName = a.LastName, Email = a.Email, Location = new LocationDTO() { Active = a.Location.Active, ID = a.Location.ID, Name = a.Location.Name }, PermissionLevel = a.PermissionLevel })); return(adminsDTO); } catch (Exception ex) { _logger.ErrorException("Unable to get list of admins", ex); return(new List <AdminDTO>()); } }
public ISession BeginOperation() { try { session = PersistenceManager.Istance.GetSession(); if (session.Transaction.IsActive) { isInternalTransaction = false; tx = session.Transaction; logger.Debug(GetCallerClassDotMethod() + " si è agganciato alla transazione " + tx.GetHashCode()); } else { isInternalTransaction = true; tx = session.Transaction; tx.Begin(); logger.Debug("Transazione " + tx.GetHashCode() + " creata da " + GetCallerClassDotMethod()); } logger.Debug("La sessione è " + session.GetHashCode()); return(session); } catch (Exception ex) { string msg = "Errore nell'apertura dell'operazione"; logger.ErrorException(msg, ex); throw new Exception(msg, ex); } }
public IList <Viaggio> GetProposteAgenzia(Agenzia agenzia) { var ar = new AgenziaRepository(); using (var om = new OperationManager()) { try { var session = om.BeginOperation(); logger.Info("Recupero dei viaggi proposti dall'agenzia {0}", agenzia); var viaggi = session.Query <Viaggio>() .Where(v => v.Agenzia.Id == agenzia.Id) .ToList(); logger.Debug("Viaggi proposti: {0}", viaggi.Count); om.CommitOperation(); return(viaggi); } catch (Exception ex) { om.RollbackOperation(); string msg = String.Format("Impossibile recuperare i viaggi proposti dall'agenzia {0}", agenzia); logger.ErrorException(msg, ex); throw new Exception(msg, ex); } } }
public ISession BeginOperation() { try { session = PersistenceManager.Istance.GetSession(); if (session.Transaction.IsActive) { isInternalTransaction = false; tx = session.Transaction; logger.Debug(GetCallerClassDotMethod() + " hooked to the transaction " + tx.GetHashCode()); } else { isInternalTransaction = true; tx = session.Transaction; tx.Begin(); logger.Debug("Transaction " + tx.GetHashCode() + " created by " + GetCallerClassDotMethod()); } logger.Debug("Session is " + session.GetHashCode()); return(session); } catch (Exception ex) { string msg = "Error beginning the operation"; logger.ErrorException(msg, ex); throw new Exception(msg, ex); } }
static void RunMetrics(SyntaxParser parser, AnalysisModel analysisModel, ResultModel result) { MetricInfo metricInfo = MetricInfo.FromParsers(true, parser); if (analysisModel.RunIndicatorMetrics) { foreach (ConstructIndicator indicator in Enum.GetValues(typeof(ConstructIndicator))) { try { MetricResult <bool> metricResult = new MetricResult <bool>(); metricResult.Occurences = metricInfo.GetOccurrences(indicator); metricResult.Result = metricResult.Occurences.Count() > 0; result.IndicatorMetricsResult.Add(indicator, metricResult); } catch (Exception ex) { logger.ErrorException(string.Format("Metrics \"{0}\" failed", indicator), ex); } } } if (analysisModel.RunQuantityMetrics) { foreach (Quantity quantity in Enum.GetValues(typeof(Quantity))) { try { MetricResult <int> metricResult = new MetricResult <int>(); metricResult.Result = metricInfo.GetQuantity(quantity); metricResult.Occurences = metricInfo.GetOccurrences(quantity); result.QuantityMetricsResult.Add(quantity, metricResult); } catch (Exception ex) { logger.ErrorException(string.Format("Metrics \"{0}\" failed", quantity), ex); } } } if (analysisModel.RunRatingMetrics) { foreach (Rating rating in Enum.GetValues(typeof(Rating))) { try { MetricResult <double> metricResult = new MetricResult <double>(); metricResult.Result = metricInfo.GetRating(rating); metricResult.Occurences = metricInfo.GetOccurrences(rating); result.RatingMetricsResult.Add(rating, metricResult); } catch (Exception ex) { logger.ErrorException(string.Format("Metrics \"{0}\" failed", rating), ex); } } } }
public List <RoomDTO> GetAllRoomBookingsForLocation(string location, DateTime start, bool smartRoom) { List <RoomDTO> rooms = new List <RoomDTO>(); if (location == null) { List <RoomDTO> result = new List <RoomDTO>(); _logger.Debug("Location is null"); _logger.Trace(LoggerHelper.ExecutedFunctionMessage(result, location, start, smartRoom)); return(result); } List <Room> roomData = new List <Room>(); try { var availableRooms = db.Rooms.Where(x => x.Location.Name == location && x.Active == true) .OrderBy(r => r.SeatCount) .ToList(); if (smartRoom) { availableRooms = availableRooms.Where(r => r.SmartRoom == true).ToList(); } roomData.AddRange(availableRooms); roomData.ForEach(x => rooms.Add(new RoomDTO() { ID = x.ID, RoomName = x.RoomName, PhoneCount = x.PhoneCount, ComputerCount = x.ComputerCount, SeatCount = x.SeatCount, SmartRoom = x.SmartRoom, Bookings = x.Bookings.Where(b => b.StartDate.Date == start.Date).Select(b => { BookingDTO bDto = new BookingDTO() { ID = b.ID, Owner = b.Owner, StartDate = b.StartDate, EndDate = b.EndDate, IsSmartMeeting = b.IsSmartMeeting }; return(bDto); }).ToList() })); } catch (Exception ex) { _logger.ErrorException("Unable to get available rooms for location: " + location, ex); } _logger.Trace(LoggerHelper.ExecutedFunctionMessage(rooms, location, start, smartRoom)); return(rooms); }
public bool Insert(OLWQConfigEntity configData) { try { return(dal.Insert(configData)); } catch (Exception ex) { logger.ErrorException("Insert", ex); return(false); } }
public string GetParm(string key) { try { return(dal.GetParm(key)); } catch (Exception ex) { logger.ErrorException("GetParm", ex); return(""); } }
private void _Start(T outputDevice) { if (_CanStart(outputDevice)) { try { _StartDevice(outputDevice); } catch (Exception ex) { Logging.ErrorException("Error starting device " + outputDevice.Name, ex); } } }
//获取最大ID public int GetMaxId() { try { return(dal.GetMaxId()); } catch (Exception ex) { logger.ErrorException("GetMaxId", ex); return(-1); } }
/// <summary> /// aspx, ashx의 <see cref="HttpContext"/>로부터 XdsRequestDocument를 만들고, /// 처리를 수행 한 후, XdsResponseDocument를 HttpContext의 Response.OutputStream에 Write를 수행합니다. /// </summary> /// <param name="context"></param> public static void Execute(HttpContext context) { context.ShouldNotBeNull("context"); if (IsDebugEnabled) { log.Debug(@"Execution for request from HttpContext is starting..."); } var request = context.Request; var productName = request.GetProductName(); var compress = request.GetUseCompress(); var security = request.GetUseSecurity(); var serializer = XmlDataServiceTool.GetSerializer(compress, security); XdsResponseDocument result = null; try { CheckProductExists(productName); Guard.Assert(request.TotalBytes > 0, "처리할 요청정보가 제공되지 않았습니다."); var requestBytes = request.InputStream.ToBytes(); var xdsRequest = ((byte[])serializer.Deserialize(requestBytes)).ConvertToXdsRequestDocument(); // var xdsRequest = XmlTool.Deserialize<XdsRequestDocument>(request.InputStream); result = Execute(xdsRequest, productName); } catch (Exception ex) { if (log.IsErrorEnabled) { log.ErrorException("요청처리 중 예외가 발생했습니다.", ex); } // 예외정보를 Client에게도 보낸다. result = result ?? new XdsResponseDocument(); result.ReportError(ex); } finally { if (result != null) { WriteResponse(context.Response, result, serializer); } } if (IsDebugEnabled) { log.Debug("Execution for request from HttpContext is finished!!!"); } }
private static IEnumerable <IModuleDescriptor> _LoadModuleDescriptors(IEnumerable <string> filePaths) { List <IModuleDescriptor> descriptors = new List <IModuleDescriptor>(); foreach (string filePath in filePaths) { try { // Determine what kind of module it is so its descriptor can be added // to that implementation's descriptor list. ModuleImplementation moduleImplementation = _FindImplementation(filePath); if (moduleImplementation == null) { Logging.Error(string.Format("File {0} was not loaded because its module type could not be determined.", filePath)); continue; } // Try to get descriptors. IEnumerable <IModuleDescriptor> descriptorsFound = _LoadModuleDescriptors(filePath); descriptors.AddRange(descriptorsFound); _moduleImplementationDescriptors[moduleImplementation].AddRange(descriptorsFound); } catch (BadImageFormatException) { } catch (ReflectionTypeLoadException ex) { foreach (Exception loaderException in ex.LoaderExceptions) { Logging.Error("Loader exception:" + Environment.NewLine + loaderException.Message, loaderException); } } catch (Exception ex) { Logging.ErrorException("Error loading modules from " + filePath, ex); } } return(descriptors); }
public List <RoomDTO> GetAllRooms() { try { List <RoomDTO> roomDTOs = new List <RoomDTO>(); List <Room> rooms = _roomRepository.GetAllRooms().OrderBy(r => r.Location.Name).ThenBy(r => r.RoomName).ToList(); rooms.ForEach(x => roomDTOs.Add(new RoomDTO() { ID = x.ID, location = new LocationDTO() { ID = x.Location.ID, Name = x.Location.Name }, RoomName = x.RoomName, ComputerCount = x.ComputerCount, SeatCount = x.SeatCount, PhoneCount = x.PhoneCount, SmartRoom = x.SmartRoom, Active = x.Active })); return(roomDTOs); } catch (Exception ex) { _logger.ErrorException("Unable to get rooms.", ex); return(new List <RoomDTO>()); } }
public void LoadData(string rootDataDirectory) { FileStream stream = null; DataFileDirectory = rootDataDirectory; if (!File.Exists(DataFilepath)) { if (Directory.Exists(DataFileDirectory)) { return; } else { DataFileDirectory = DefaultDataFileDirectory; if (!File.Exists(DataFilepath)) { return; } } } try { stream = new FileStream(DataFilepath, FileMode.Open); XElement root = XElement.Load(stream); XElement versionElement = root.Element("DataFormatVersion"); if (versionElement == null) { Logging.Error("VixenApplication: loading application data: couldn't find data format version"); return; } int dataFormatVersion = int.Parse(versionElement.Value); ReadData(dataFormatVersion, root); } catch (FileNotFoundException ex) { Logging.WarnException("VixenApplication: loading application data, but couldn't find file", ex); } catch (Exception ex) { Logging.ErrorException("VixenApplication: error loading application data", ex); } finally { if (stream != null) { stream.Close(); } } }
public HashSet <Guid> UpdateCacheCompileContext(TimeSpan time) { HashSet <Guid> elementsAffected = null; _stopwatch.Restart(); try { elementsAffected = _preCachingSequenceContext.UpdateElementStates(time); } catch (Exception ee) { Logging.ErrorException(ee.Message, ee); } _contextUpdateTimeValue.Set(_stopwatch.ElapsedMilliseconds); return(elementsAffected); }
/// <summary> /// 发送到服务 /// </summary> /// <param name="msg"></param> public void SendMessage(SocketEntity msmqEntity) { try { if (msmqEntity == null) { return; } if (SocketHelper.IsSocketConnected_Poll(socket)) { string strmsg = JSONSerialize.JsonSerialize_Newtonsoft(msmqEntity); byte[] data = Encoding.UTF8.GetBytes(SocketHelper.SocketMsgSplit + strmsg + SocketHelper.SocketMsgSplit); socket.BeginSend(data, 0, data.Length, 0, new AsyncCallback(SendCallback), socket); OnSockConnEvent(new SocketStatusEventArgs(true)); } else { Connect(); } } catch (Exception ex) { logger.ErrorException("SendMessage", ex); } }
public IOutputFilterModuleInstance ReadObject(XElement element) { try { Guid?typeId = XmlHelper.GetGuidAttribute(element, ATTR_TYPE_ID); if (typeId == null) { return(null); } Guid?instanceId = XmlHelper.GetGuidAttribute(element, ATTR_INSTANCE_ID); if (instanceId == null) { return(null); } IOutputFilterModuleInstance outputFilter = Modules.ModuleManagement.GetOutputFilter(typeId); if (outputFilter != null) { outputFilter.InstanceId = instanceId.Value; } return(outputFilter); } catch (Exception e) { logging.ErrorException("Error loading Output Filter from XML", e); return(null); } }
/// <summary> /// Devart dotConnecto for Oracle이 NHibernate 3.2에서 제대로 작동하려면 Devart.Data.Oracle.OracleUtils.OracleClientCompatible = true 로 설정해주어야 합니다. /// 이를 수행하여 NH 3.2 이상에서도 제대로 동작하도록 합니다. /// 참고: http://www.devart.com/forums/viewtopic.php?t=21676 /// </summary> private void Intialize() { // NOTE: NHibernate 3.2 이상에서 Devart Oracle의 Parameter 작업이 이상 작동하는 것을 교정하기 위해 OracleClientCompatible 필드 값을 True로 설정합니다. // 참고: http://www.devart.com/forums/viewtopic.php?t=21676 const string DevartDataOracleAssemblyName = "Devart.Data.Oracle"; const string OracleUtilsTypeName = "Devart.Data.Oracle.OracleUtils"; const string OracleClientCompatibleFieldName = "OracleClientCompatible"; if (log.IsInfoEnabled) { log.Info("Devart.Data.Oracle.OracleUtils.OracleClientCompatible 값을 true로 설정합니다..."); log.Info("NHibernate 3.2 이상에서 Devart Oracle의 Parameter 작업이 이상 작동하는 것을 교정하기 위해 OracleClientCompatible 필드 값을 True로 설정합니다."); } try { var asm = Assembly.Load(DevartDataOracleAssemblyName); var type = asm.GetType(OracleUtilsTypeName); var fi = type.GetField(OracleClientCompatibleFieldName, BindingFlags.Public | BindingFlags.Static); fi.SetValue(null, true); } catch (Exception ex) { if (log.IsErrorEnabled) { log.ErrorException("Devart.Data.Oracle.OracleUtils.OracleClientCompatible 값을 true로 설정하는데 예외가 발생했습니다.", ex); } throw; } }
static WindsorHttpModule() { if (log.IsInfoEnabled) { log.Info("IoCHttpModule에서 IoC 를 초기화를 시작합니다... "); } try { if (IoC.IsNotInitialized) { IoC.Initialize(); if (log.IsInfoEnabled) { log.Info("IoCHttpModule에서 IoC 를 초기화를 완료했습니다!!!"); } } } catch (Exception ex) { if (log.IsErrorEnabled) { log.ErrorException("IoCHttpModule에서 IoC 초기화시에 예외가 발생했습니다.", ex); } throw; } }
/// <summary> /// HttpHandler의 작업의 메인 메소드입니다. 재정의 하여 원하는 기능을 수행하되, 제일 첫번째에 부모 클래스의 메소들를 호출해주어야 합니다. /// </summary> /// <param name="context"></param> protected override void DoProcessRequest(HttpContext context) { context.ShouldNotBeNull("context"); if (IsDebugEnabled) { log.Debug(@"요청정보를 받아 처리를 시작합니다..."); } try { var productName = context.Request[HttpParams.Product].AsText(); if (IsDebugEnabled) { log.Debug("ProductName=[{0}]에 대한 요청 처리를 접수했습니다...", productName); } var adapter = XmlDataTool.ResolveXmlDataManagerAdapter(productName); var responseBytes = adapter.Execute(context.Request.InputStream.ToBytes()); context.WriteResponse(responseBytes); if (IsDebugEnabled) { log.Debug("ProductName=[{0}]에 대한 요청 처리를 완료하였습니다!!!", productName); } } catch (Exception ex) { if (log.IsErrorEnabled) { log.ErrorException("요청을 처리하는 동안 예외가 발생했습니다.", ex); } } }
public XElement ReadFile(string filePath) { if (!File.Exists(filePath)) { return(null); } using (FileStream fileStream = new FileStream(filePath, FileMode.Open)) { using (StreamReader reader = new StreamReader(fileStream)) { try { return(XElement.Load(reader)); } catch (System.Exception ex) { Logging.ErrorException("Error loading '" + filePath + "'.", ex); } } } // if there was an error loading the file, back up the 'bad' one, so the user can manually recover it later if needed. // This may not be needed in all cases, since this class is quite generic, but it will do for now. Can be refactored later if needed. if (File.Exists(filePath)) { File.Copy(filePath, string.Format("{0}.{1}", filePath, System.DateTime.Now.ToFileTime())); } return(null); }
private static void ScriptCommand(ScriptCommand command, IManager manager) { // Get the avatar of the related player. var avatar = ((AvatarSystem)manager.GetSystem(AvatarSystem.TypeId)).GetAvatar(command.PlayerNumber); // Make sure we have the player's avatar. if (avatar <= 0) { return; } // We only have one engine in a potential multi threaded // environment, so make sure we only access it once at a // time. var scriptSystem = (ScriptSystem)manager.GetSystem(ScriptSystem.TypeId); scriptSystem.Call("setExecutingPlayer", command.PlayerNumber); try { var result = scriptSystem.Execute(command.Script); if (result != null) { scriptSystem.Call("print", result); } } catch (InvalidOperationException ex) { Logger.ErrorException("Error executing script.\n", ex); } finally { scriptSystem.Call("setExecutingPlayer", -1); } }