internal static ErrorMessage GetErrorMessage(IMessage message, Exception exception) { MessageException me = null; if (exception is MessageException) me = exception as MessageException; else me = new MessageException(exception); ErrorMessage errorMessage = me.GetErrorMessage(); if (message.clientId != null) errorMessage.clientId = message.clientId; else errorMessage.clientId = Guid.NewGuid().ToString("D"); errorMessage.correlationId = message.messageId; errorMessage.destination = message.destination; if (exception is SecurityException) errorMessage.faultCode = ErrorMessage.ClientAuthenticationError; if (exception is UnauthorizedAccessException) errorMessage.faultCode = ErrorMessage.ClientAuthorizationError; return errorMessage; }
private IList Batch(DataMessage dataMessage) { ArrayList result = new ArrayList(); IList messageBatch = dataMessage.body as IList; for (int i = 0; i < messageBatch.Count; i++) { IMessage message = messageBatch[i] as IMessage; try { if (message is UpdateCollectionMessage) { result.Add(UpdateCollection(message as UpdateCollectionMessage, messageBatch)); } else { object obj = Invoke(message); result.Add(obj); } } catch (DataSyncException dataSyncException) { DataErrorMessage dataErrorMessage = dataSyncException.GetErrorMessage() as DataErrorMessage; dataErrorMessage.cause = message as DataMessage; dataErrorMessage.correlationId = message.messageId; dataErrorMessage.destination = message.destination; result.Add(dataErrorMessage); } catch (Exception exception) { MessageException messageException = new MessageException(exception); ErrorMessage errorMessage = messageException.GetErrorMessage(); errorMessage.correlationId = message.messageId; errorMessage.destination = message.destination; result.Add(errorMessage); } } return(result); }
private IList Batch(DataMessage dataMessage) { ArrayList list = new ArrayList(); IList body = dataMessage.body as IList; for (int i = 0; i < body.Count; i++) { IMessage message = body[i] as IMessage; try { if (message is UpdateCollectionMessage) { list.Add(this.UpdateCollection(message as UpdateCollectionMessage, body)); } else { object obj2 = this.Invoke(message); list.Add(obj2); } } catch (DataSyncException exception) { DataErrorMessage errorMessage = exception.GetErrorMessage() as DataErrorMessage; errorMessage.cause = message as DataMessage; errorMessage.correlationId = message.messageId; errorMessage.destination = message.destination; list.Add(errorMessage); } catch (Exception exception2) { ErrorMessage message3 = new MessageException(exception2).GetErrorMessage(); message3.correlationId = message.messageId; message3.destination = message.destination; list.Add(message3); } } return(list); }
/// <summary> /// Get Lowest Common Ancestor /// </summary> /// <param name="values">Binary Tree</param> /// <param name="first">Node one of Lowest Common Ancestor</param> /// <param name="second">Node two of Lowest Common Ancestor</param> /// <returns></returns> public long GetLowestCommonAncestor(List <long> values, long first, long second) { try { BinaryTree binaryTree = AddBinaryTree(values); return(LCA(binaryTree.Root, first, second)); } catch (System.Exception ex) { MessageException error = new MessageException { Text = ex.Message, ID = "200" }; log.Error(error.ID + ": An error has occurred in GetLowestCommonAncestor: " + ex.Message + "; " + ex.InnerException); throw new FaultException <MessageException>(error, error.ID + ": An error has occurred in GetLowestCommonAncestor: " + ex.Message + "; " + ex.InnerException); } finally { log.Info("The Lowest Common Ancestor algorithm executed successfully"); } }
public void LogOut(int pageId = 0) { if (null != UserSession) { using (ITransaction tx = PersistenceSession.BeginTransaction()) { try { UserSession.SessionPeriod.To = DateTime.Now; UserSession.LogoutMessage = "Logout"; UserSession.Save(this); Log(0, pageId, 0, MessageException.AuthenMessage.Logout, MessageException.Success(User.ID.ToString())); tx.Commit(); } catch (Exception ex) { Log(0, pageId, 0, MessageException.AuthenMessage.Logout, MessageException.Fail(ex.Message)); throw; } } } }
public void OnException(ExceptionContext context) { if (context.Exception != null) { context.HttpContext.Response.ContentType = "application/json"; switch (context.Exception) { case Auth0.Core.Exceptions.ApiException _: Auth0.Core.Exceptions.ApiException res = (context.Exception as Auth0.Core.Exceptions.ApiException); context.HttpContext.Response.StatusCode = res.ApiError.StatusCode; context.Result = new JsonResult(new MessageResponse { Message = res.ApiError.Message }); break; case FileNotFoundException _: context.HttpContext.Response.StatusCode = 404; context.Result = new JsonResult(new MessageResponse { Message = "Item not found!" }); break; case MessageException _: context.HttpContext.Response.StatusCode = 400; MessageException e = context.Exception as MessageException; context.Result = new JsonResult(new MessageResponse { Message = e.Message }); break; default: context.Result = new StatusCodeResult(500); break; } } }
public JsonResult Delete(long id) { try { Strategic strategic = Strategic.Get(SessionContext, id); if (strategic == null) { SessionContext.Log(0, this.pageID, 0, MessageException.StrategicMessage.Delete, MessageException.Null("The static method Get return null, ID : " + id)); return(Json(new { Success = false, Message = MessageException.Error }, JsonRequestBehavior.AllowGet)); } using (ITransaction tx = SessionContext.PersistenceSession.BeginTransaction()) { try { strategic.EffectivePeriod = new TimeInterval(TimeInterval.MaxDate, TimeInterval.MinDate); strategic.UpdateAction = new UserAction(SessionContext.User); //strategic.Delete(SessionContext); tx.Commit(); SessionContext.Log(0, this.pageID, 0, MessageException.StrategicMessage.Delete, MessageException.Success(id.ToString())); } catch (Exception ex) { tx.Rollback(); SessionContext.LogButNotFlush(0, this.pageID, 0, MessageException.StrategicMessage.Delete, MessageException.Fail(ex.Message)); return(Json(new { Success = false, Message = MessageException.Error }, JsonRequestBehavior.AllowGet)); } } } catch (Exception ex) { SessionContext.LogButNotFlush(0, this.pageID, 0, MessageException.StrategicMessage.Delete, MessageException.Fail(ex.Message)); return(Json(new { Success = false, Message = MessageException.Error }, JsonRequestBehavior.AllowGet)); } return(Json(new { Success = true, Message = "ลบนโยบายเชิงยุทธศาสตร์ เรียบร้อย" }, JsonRequestBehavior.AllowGet)); }
public static async Task <DigitalPlatform.HTTP.HttpResponse> WebCall(DigitalPlatform.HTTP.HttpRequest request, string transferEncoding, TimeSpan timeout) { // 从 request.Url 中解析出 remoteUserName string remoteUserName = request.Url; if (string.IsNullOrEmpty(remoteUserName) == false && remoteUserName[0] == '/') { remoteUserName = remoteUserName.Substring(1); } { // 只取第一级作为对方用户名 List <string> parts = StringUtil.ParseTwoPart(remoteUserName, "/"); remoteUserName = parts[0]; } WebData data = MessageUtility.BuildWebData(request, transferEncoding); string id = Guid.NewGuid().ToString(); WebCallRequest param = new WebCallRequest(id, transferEncoding, data, true, true); // CancellationToken cancel_token = new CancellationToken(); try { // Console.WriteLine("Begin WebCall"); #if NO MessageConnection connection = _channels.GetConnectionTaskAsync( Url, remoteUserName).Result; WebCallResult result = connection.WebCallTaskAsync( remoteUserName, param, new TimeSpan(0, 1, 10), // 10 秒 _cancel.Token).Result; #endif MessageConnection connection = await _messageChannels.GetConnectionTaskAsync( Url, remoteUserName, // 每个图书馆一根独立通道 true, true); // 采用 incUseCount。使用后要归还 WebCallResult result = null; try { result = await connection.WebCallTaskAsync( remoteUserName, param, timeout == TimeSpan.MinValue?new TimeSpan(0, 1, 10) : timeout, // 1分10 秒 _cancel.Token); } finally { _messageChannels.ReturnConnection(connection); } // Console.WriteLine("End WebCall result=" + result.Dump()); if (result.Value == -1) { // 构造一个 500 错误响应包 return(new DigitalPlatform.HTTP.HttpResponse("500", "Router Error: " + WebUtility.UrlEncode(result.ErrorInfo), result.ErrorInfo)); } return(MessageUtility.BuildHttpResponse(result.WebData, transferEncoding)); } catch (AggregateException ex) { string code = "500"; WriteErrorLog("1(测试): " + ex.ToString()); // 2016/10/29 string error = ExceptionUtil.GetExceptionText(ex); Console.WriteLine("Exception: " + error); MessageException ex1 = ExceptionUtil.FindInnerException(ex, typeof(MessageException)) as MessageException; if (ex1 != null && ex1.ErrorCode.ToLower() == "unauthorized") { error = "dp2Router 针对 dp2MServer 的账户 '" + ex1.UserName + "' 登录失败"; code = "401"; } WriteErrorLog("1: " + error); // 构造一个错误代码响应包 return(new DigitalPlatform.HTTP.HttpResponse( code, "Router Error: " + WebUtility.UrlEncode(error), error)); } catch (Exception ex) { WriteErrorLog("2: " + ExceptionUtil.GetExceptionText(ex)); // 构造一个 500 错误响应包 return(new DigitalPlatform.HTTP.HttpResponse( "500", "Router Error: " + WebUtility.UrlEncode(ex.Message), ExceptionUtil.GetExceptionText(ex))); } }
private string GetMasterFileName(ZipFile zip) { string master = null; foreach (ZipEntry entry in zip) { logger.Log(LogLevel.Debug, "ZipEntry : {0}", entry.FileName); if (entry.FileName.EndsWith(".master", StringComparison.OrdinalIgnoreCase)) { if (master == null) { master = entry.FileName; } else { // zip file cannot have more than one master. MessageException me = new MessageException( Resource.ResourceManager.GetLiteral("Admin.Templates.Zip.MoreThanOneMaster") ); throw me; } } } if (master == null) { // must have atleast one master file. MessageException me = new MessageException( Resource.ResourceManager.GetLiteral("Admin.Templates.Zip.NoMaster") ); throw me; } return master; }
public JsonResult Delete(long id) { Announce announce = Announce.Get(SessionContext, id); if (announce == null) { SessionContext.Log(0, this.pageID, 0, MessageException.AnnounceMessage.Delete, MessageException.Null("The static method Get return null, ID : " + id)); return(Json(new { Success = false, Message = MessageException.Error }, JsonRequestBehavior.AllowGet)); } using (ITransaction tx = SessionContext.PersistenceSession.BeginTransaction()) { try { announce.Delete(SessionContext); tx.Commit(); SessionContext.Log(0, this.pageID, 0, MessageException.AnnounceMessage.Delete, MessageException.Success(id.ToString())); } catch (Exception ex) { tx.Rollback(); SessionContext.Log(0, this.pageID, 0, MessageException.AnnounceMessage.Delete, MessageException.Fail(ex.Message)); return(Json(new { Success = false, Message = MessageException.Error }, JsonRequestBehavior.AllowGet)); } } return(Json(new { Success = true, Message = "ลบประกาศ เรียบร้อย" }, JsonRequestBehavior.AllowGet)); }
public JsonResult GetAnnounces() { IList <Announce> announces = null; IList <AnnounceViewModel> announceViewModels = null; try { announces = Announce.GetAll(SessionContext); announceViewModels = announces.Select(x => new AnnounceViewModel { Id = x.ID, HeadLine = x.HeadLine, Content = x.Content }).ToList(); } catch (Exception ex) { SessionContext.Log(0, this.pageID, 0, MessageException.AnnounceMessage.Gets, MessageException.Fail(ex.Message)); } return(Json(announceViewModels, JsonRequestBehavior.AllowGet)); }
public JsonResult DeleteUsers(string id) { StringBuilder message = new StringBuilder(); message.Append("<b>ลบ บัตรประชาชน</b> <br/>"); int successCount = 0; //int failCount = 0; string[] param = id.Split(','); try { if (string.IsNullOrEmpty(id)) { SessionContext.Log(0, this.pageID, 0, MessageException.UserMessage.Delete, MessageException.Fail("The ID is Emrpty")); return(Json(new { Success = false, Message = MessageException.PleaseSelectUser }, JsonRequestBehavior.AllowGet)); } message.Append("<ul>"); //Add logic here for (int i = 0; i < param.Length; i++) { iSabaya.SelfAuthenticatedUser u = SessionContext.PersistenceSession.Get <iSabaya.SelfAuthenticatedUser>(Int64.Parse(param[i])); if (u != null) { using (ITransaction tx = SessionContext.PersistenceSession.BeginTransaction()) { try { u.EffectivePeriod = new iSabaya.TimeInterval { ExpiryDate = DateTime.Now }; u.UpdateAction = new iSabaya.UserAction(SessionContext.User); u.Persist(SessionContext); tx.Commit(); SessionContext.Log(0, this.pageID, 0, MessageException.UserMessage.Delete, MessageException.Success(id)); successCount++; message.Append(string.Format("<li>{0}</li>", u.Person.OfficialIDNo)); } catch (Exception ex) { tx.Rollback(); SessionContext.Log(0, this.pageID, 0, MessageException.UserMessage.Delete, MessageException.Fail(ex.Message)); } } } } message.Append("</ul>"); } catch (Exception ex) { SessionContext.Log(0, this.pageID, 0, MessageException.UserMessage.Delete, MessageException.Fail(ex.Message)); return(Json(new { Success = false, Message = MessageException.Error }, JsonRequestBehavior.AllowGet)); } message.Append(string.Format("ลบผู้ที่ถูกเลือกสำเร็จ {0} / {1} แถว", successCount, param.Length)); return(Json(new { Success = true, Message = message.ToString() }, JsonRequestBehavior.AllowGet)); }
public void WriteMessage(AMFMessage amfMessage) { try { base.WriteShort(amfMessage.Version); int headerCount = amfMessage.HeaderCount; base.WriteShort(headerCount); for (int i = 0; i < headerCount; i++) { this.WriteHeader(amfMessage.GetHeaderAt(i), ObjectEncoding.AMF0); } int bodyCount = amfMessage.BodyCount; base.WriteShort(bodyCount); for (int i = 0; i < bodyCount; i++) { ResponseBody responseBody = amfMessage.GetBodyAt(i) as ResponseBody; if (responseBody != null && !responseBody.IgnoreResults) { //Try to catch serialization errors if (this.BaseStream.CanSeek) { long position = this.BaseStream.Position; try { responseBody.WriteBody(amfMessage.ObjectEncoding, this); } catch (Exception exception) { this.BaseStream.Seek(position, SeekOrigin.Begin); //this.BaseStream.Position = position; #if !SILVERLIGHT if (log.IsFatalEnabled) { log.Fatal(__Res.GetString(__Res.Amf_SerializationFail), exception); } #endif ErrorResponseBody errorResponseBody; if (responseBody.RequestBody.IsEmptyTarget) { object content = responseBody.RequestBody.Content; if (content is IList) { content = (content as IList)[0]; } IMessage message = content as IMessage; MessageException messageException = new MessageException(exception); messageException.FaultCode = __Res.GetString(__Res.Amf_SerializationFail); errorResponseBody = new ErrorResponseBody(responseBody.RequestBody, message, messageException); } else { errorResponseBody = new ErrorResponseBody(responseBody.RequestBody, exception); } try { errorResponseBody.WriteBody(amfMessage.ObjectEncoding, this); } #if !SILVERLIGHT catch (Exception exception2) { if (log.IsFatalEnabled) { log.Fatal(__Res.GetString(__Res.Amf_ResponseFail), exception2); } throw; } #else catch (Exception) { throw; } #endif } } else { responseBody.WriteBody(amfMessage.ObjectEncoding, this); } } else { AMFBody amfBody = amfMessage.GetBodyAt(i); FluorineFx.Util.ValidationUtils.ObjectNotNull(amfBody, "amfBody"); amfBody.WriteBody(amfMessage.ObjectEncoding, this); } } } #if !SILVERLIGHT catch (Exception exception) { if (log.IsFatalEnabled) { log.Fatal(__Res.GetString(__Res.Amf_SerializationFail), exception); } throw; } #else catch (Exception) { throw; } #endif }
public JsonResult Save(string name) { try { if (string.IsNullOrEmpty(name)) { SessionContext.Log(0, this.pageID, 0, MessageException.StrategicMessage.Save, MessageException.Fail("The name is emptry.")); return(Json(new { Success = false, Message = MessageException.Error }, JsonRequestBehavior.AllowGet)); } using (ITransaction tx = SessionContext.PersistenceSession.BeginTransaction()) { try { Strategic strategic = new Strategic { Name = name, }; strategic.CreateAction = new UserAction(SessionContext.User); strategic.EffectivePeriod = TimeInterval.EffectiveNow; SessionContext.Persist(strategic); tx.Commit(); SessionContext.Log(0, this.pageID, 0, MessageException.StrategicMessage.Save, MessageException.Success()); } catch (Exception ex) { tx.Rollback(); SessionContext.LogButNotFlush(0, this.pageID, 0, MessageException.StrategicMessage.Save, MessageException.Fail(ex.Message)); return(Json(new { Success = false, Message = MessageException.Error }, JsonRequestBehavior.AllowGet)); } } } catch (Exception ex) { SessionContext.LogButNotFlush(0, this.pageID, 0, MessageException.StrategicMessage.Save, MessageException.Fail(ex.Message)); return(Json(new { Success = false, Message = MessageException.Error }, JsonRequestBehavior.AllowGet)); } return(Json(new { Success = true, Message = "เพิ่มนโยบายเชิงยุทธศาสตร์ เรียบร้อย" }, JsonRequestBehavior.AllowGet)); }
public JsonResult UnlogUsers(string id) { StringBuilder message = new StringBuilder(); message.Append("<b>ปลดล๊อก บัตรประชาชน</b> <br/>"); int successCount = 0; //int failCount = 0; string[] param = id.Split(','); try { if (string.IsNullOrEmpty(id)) { SessionContext.Log(0, this.pageID, 0, MessageException.UserMessage.Unlog, MessageException.Fail("The ID is Emrpty")); return(Json(new { Success = false, Message = MessageException.PleaseSelectUser }, JsonRequestBehavior.AllowGet)); } message.Append("<ul>"); //Add logic here for (int i = 0; i < param.Length; i++) { IList <iSabaya.UserSession> userSessions = SessionContext.PersistenceSession .QueryOver <iSabaya.UserSession>() .Where(us => us.User.ID == long.Parse(param[i]) && us.SessionPeriod.To == iSabaya.TimeInterval.MaxDate) .List(); if (userSessions.Count > 0) { successCount++; message.Append(string.Format("<li>{0}</li>", userSessions[0].User.Person.OfficialIDNo)); } foreach (iSabaya.UserSession us in userSessions) { using (ITransaction tx = SessionContext.PersistenceSession.BeginTransaction()) { try { us.SessionPeriod.To = DateTime.Now; us.Save(SessionContext); tx.Commit(); SessionContext.Log(0, this.pageID, 0, MessageException.UserMessage.Unlog, MessageException.Success(us.ID.ToString())); } catch (Exception ex) { tx.Rollback(); SessionContext.Log(0, this.pageID, 0, MessageException.UserMessage.Unlog, MessageException.Fail(ex.Message)); } } } } message.Append("</ul>"); } catch (Exception ex) { SessionContext.Log(0, this.pageID, 0, MessageException.UserMessage.Unlog, MessageException.Fail(ex.Message)); return(Json(new { Success = false, Message = MessageException.Error }, JsonRequestBehavior.AllowGet)); } message.Append(string.Format("ปลดล๊อกผู้ที่ถูกเลือกสำเร็จ {0} / {1} แถว", successCount, param.Length)); return(Json(new { Success = true, Message = message.ToString() }, JsonRequestBehavior.AllowGet)); }
public JsonResult GetStrategic(long id) { try { Strategic strategic = Strategic.Get(SessionContext, id); if (strategic == null) { SessionContext.Log(0, this.pageID, 0, MessageException.StrategicMessage.Get, MessageException.Null("The static method Get return null, ID : " + id)); return(Json(new { Success = false, Message = MessageException.Error }, JsonRequestBehavior.AllowGet)); } StrategicViewModel strategicViewModel = new StrategicViewModel { ID = strategic.ID, Name = strategic.Name, }; return(Json(new { Success = true, strategicViewModel }, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { SessionContext.Log(0, this.pageID, 0, MessageException.StrategicMessage.Get, MessageException.Fail(ex.Message)); return(Json(new { Success = false, Message = MessageException.Error }, JsonRequestBehavior.AllowGet)); } }
public static App Install(string zipLocation) { #region argument if (string.IsNullOrEmpty(zipLocation)) { throw new ArgumentNullException("zipLocation"); } //must be zip file if (!zipLocation.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException("zipLocation : {0} is not a zip file", zipLocation); } if (!File.Exists(zipLocation)) { throw new ArgumentException("zipLocation : {0} not found", zipLocation); } HttpContext context = HttpContext.Current; if (context == null) { // cannot install without the HttpContext throw new InvalidOperationException("cannot perform without HttpContext"); } #endregion logger.Log(LogLevel.Debug, "Install called for - {0}", zipLocation); // unzip the files and delete the uploaded file string appFolder = Utility.GetUniqueString(); // get the install location for appFolder string appExtractPath = GetInstallLocation(appFolder); logger.Log(LogLevel.Debug, "App files uploaded at : {0}.", appExtractPath); App app; bool appValid = true; ExtractZip(zipLocation, appExtractPath); try { string manifest = null; #region manifest check if (!GetManifestContents(appExtractPath, out manifest)) { appValid = false; // manifest file is missing for the app. MessageException me = new MessageException( Jardalu.Ratna.Web.Resource.ResourceManager.GetLiteral("Admin.Apps.ManifestMissing") ); throw me; } #endregion app = GetAppFromManifest(manifest, out appValid); bool isUpgrade = false; bool isOverride = false; // check if the app is an upgrade/reload path App existingApp = AppStore.Instance.GetApp(app.UniqueId); if (existingApp != null) { if (existingApp.UniqueId == app.UniqueId) { isOverride = true; //check for version for upgrade if (app.Version > existingApp.Version) { isUpgrade = true; } else if (app.Version < existingApp.Version) { // throw because the app cannot be downgraded. } } } //set the app location app.Location = appFolder; logger.Log(LogLevel.Debug, "Saving the created app"); app.Update(); logger.Log(LogLevel.Info, "App saved successfully"); //remove the existing app if (isUpgrade || isOverride) { // app has moved to a new location, delete from older folder string existingAppFolder = GetInstallLocation(existingApp.Location); logger.Log(LogLevel.Info, "Removing bits from {0} because app is upgraded.", existingAppFolder); Directory.Delete(existingAppFolder, true); } } finally { //remove the uploaded folder, if the app was not valid if (!appValid) { logger.Log(LogLevel.Info, "Cleaning folder {0} as app is invalid.", appExtractPath); Directory.Delete(appExtractPath, true); } } return app; }
private static App GetAppFromManifest(string manifest, out bool appValid) { XmlDocument document = new XmlDocument(); App app = null; appValid = true; try { logger.Log(LogLevel.Debug, "Loading app manifest xml"); document.LoadXml(manifest); logger.Log(LogLevel.Debug, "Parsing app manifest xml to create app"); app = AppManifestParser.Parse(document); } catch (Exception exception) { // unable to create app. appValid = false; //log the failure logger.Log(LogLevel.Info, "Creating app failed - {0}.", exception); // manifest file is missing for the app. MessageException me = new MessageException( Jardalu.Ratna.Web.Resource.ResourceManager.GetLiteral("Admin.Apps.UnableToCreateApp") ); throw me; } return app; }
public SignUpException(MessageException<SignupRs> signupMessageException) { errors = signupMessageException.Response.signupErrors; }
protected virtual void OnConnectFailed(MessageException exception) { ConnectFailed(this, new MessageExceptionEventArgs(exception)); }
public JsonResult GetStrategics() { IList <Strategic> strategics = null; IList <StrategicViewModel> strategicViewModels = null; try { strategics = Strategic.GetEffectives(SessionContext); strategicViewModels = strategics.Select(x => new StrategicViewModel { ID = x.ID, Name = x.Name, }).ToList(); } catch (Exception ex) { SessionContext.Log(0, this.pageID, 0, MessageException.StrategicMessage.Gets, MessageException.Fail(ex.Message)); } return(Json(strategicViewModels, JsonRequestBehavior.AllowGet)); }
private void _tdSignIner_OnLoginError(MessageException obj) { LoginTaskSource.TrySetException(obj); }
public JsonResult Search(string idcard = "", string firstname = "", string lastname = "", long ministryId = 0L, int role = 0, int status = 0, string isDelete = "") { IList <UserViewModel> userViewModels = null; try { DateTime now = DateTime.Now; bool isDel = isDelete == "2"; IList <iSabaya.SelfAuthenticatedUser> users = SessionContext.PersistenceSession.QueryOver <iSabaya.SelfAuthenticatedUser>().List(); if (!string.IsNullOrEmpty(idcard)) { users = users.Where(x => x.Person.OfficialIDNo == idcard).ToList(); } if (!string.IsNullOrEmpty(firstname)) { users = users.Where(x => x.Person.CurrentName.FirstName.Values.Any(f => f.Value == firstname)).ToList(); } if (!string.IsNullOrEmpty(lastname)) { users = users.Where(x => x.Person.CurrentName.LastName.Values.Any(l => l.Value == lastname)).ToList(); } if (ministryId > 0) { users = users.Where(x => x.Organization.ID == ministryId).ToList(); } if (role > 0) { users = users.Where(x => x.UserRoles[0].Role.Id == role).ToList(); } if (status > 0) { users = users.Where(x => x.IsDisable == (status == 1 ? false : true)).ToList(); } if (!string.IsNullOrEmpty(isDelete)) { if (isDel) { users = users.Where(x => x.EffectivePeriod.From < now && x.EffectivePeriod.To < now).ToList(); } else { users = users.Where(x => x.EffectivePeriod.From <= now && x.EffectivePeriod.To >= now).ToList(); } } //Get userSession is SingoutTS is nax date mean use is not singout IList <iSabaya.UserSession> userSessions = SessionContext.PersistenceSession .QueryOver <iSabaya.UserSession>() .Where(x => x.SessionPeriod.To == iSabaya.TimeInterval.MaxDate) .List(); userViewModels = users.Select(u => new UserViewModel { Id = u.ID, IdCard = u.Person.OfficialIDNo, FirstNameTh = u.Person.CurrentName.FirstName.GetValue("th-TH"), LastNameTh = u.Person.CurrentName.LastName.GetValue("th-TH"), IsOnline = userSessions.Any(s => s.User.ID == u.ID), IsDelete = !u.IsEffective, Status = "", IsActive = !u.IsDisable, Department = new DepartmentViewModel { ID = u.OrgUnit.ID, Name = u.OrgUnit.CurrentName.Name.GetValue("th-TH"), Code = u.OrgUnit.Code, Ministry = new MinistryViewModel { ID = u.OrgUnit.OrganizationParent.ID, Name = u.OrgUnit.OrganizationParent.CurrentName.Name.GetValue("th-TH"), Code = u.OrgUnit.OrganizationParent.Code, }, }, }).ToList(); } catch (Exception ex) { SessionContext.Log(0, this.pageID, 0, MessageException.UserMessage.Search, MessageException.Fail(ex.Message)); } return(Json(userViewModels, JsonRequestBehavior.AllowGet)); }
public JsonResult Update(long id, string code, string name) { try { if (string.IsNullOrEmpty(code) || string.IsNullOrEmpty(name)) { SessionContext.Log(0, this.pageID, 0, MessageException.DepartmentMessage.Update, MessageException.Null("The code or name is emptry.")); return(Json(new { Success = false, Message = MessageException.PleaseFillOut }, JsonRequestBehavior.AllowGet)); } OrgUnit orgUnit = OrgUnit.Find(SessionContext, id); if (orgUnit == null) { SessionContext.Log(0, this.pageID, 0, MessageException.DepartmentMessage.Update, MessageException.Fail("The static method Find return null, ID : " + id)); return(Json(new { Success = false, Message = MessageException.Error }, JsonRequestBehavior.AllowGet)); } using (ITransaction tx = SessionContext.PersistenceSession.BeginTransaction()) { try { orgUnit.Code = code.Trim(); orgUnit.CurrentName.Name = new MultilingualString("th-TH", name.Trim(), "en-US", name.Trim()); orgUnit.Persist(SessionContext); tx.Commit(); SessionContext.Log(0, this.pageID, 0, MessageException.DepartmentMessage.Update, MessageException.Success()); } catch (Exception ex) { tx.Rollback(); SessionContext.Log(0, this.pageID, 0, MessageException.DepartmentMessage.Update, MessageException.Fail(ex.Message)); return(Json(new { Success = false, Message = MessageException.Error }, JsonRequestBehavior.AllowGet)); } } } catch (Exception ex) { SessionContext.Log(0, this.pageID, 0, MessageException.DepartmentMessage.Update, MessageException.Fail(ex.Message)); return(Json(new { Success = false, Message = MessageException.Error }, JsonRequestBehavior.AllowGet)); } return(Json(new { Success = true, Message = "แก้ไขข้อมูลหน่วยงาน เรียบร้อย" }, JsonRequestBehavior.AllowGet)); }
public JsonResult GetUsers() { IList <UserViewModel> userModels = null; try { DateTime now = DateTime.Now; IList <iSabaya.SelfAuthenticatedUser> users = SessionContext.PersistenceSession.QueryOver <iSabaya.SelfAuthenticatedUser>().List(); //Get userSession is SingoutTS is nax date mean use is not singout IList <iSabaya.UserSession> userSessions = SessionContext.PersistenceSession .QueryOver <iSabaya.UserSession>() .Where(x => x.SessionPeriod.To == iSabaya.TimeInterval.MaxDate) .List(); userModels = users.Where(x => x.EffectivePeriod.From <= now && x.EffectivePeriod.To >= now) .Select(u => new UserViewModel { Id = u.ID, //No = no++, IdCard = u.Person.OfficialIDNo, FirstNameTh = u.Person.CurrentName.FirstName.GetValue("th-TH"), LastNameTh = u.Person.CurrentName.LastName.GetValue("th-TH"), IsOnline = userSessions.Any(s => s.User.ID == u.ID), IsDelete = !u.IsEffective, Address = u.Address, Status = u.UserRoles[0].Role.Code == "User" ? u.UserRoles[0].Role.Description.Split(',')[0] : u.UserRoles[0].Role.Description, Department = new DepartmentViewModel { ID = u.OrgUnit.ID, Name = u.OrgUnit.CurrentName.Name.GetValue("th-TH"), Code = u.OrgUnit.Code, Ministry = new MinistryViewModel { ID = u.OrgUnit.OrganizationParent.ID, Name = u.OrgUnit.OrganizationParent.CurrentName.Name.GetValue("th-TH"), Code = u.OrgUnit.OrganizationParent.Code, }, }, IsActive = !u.IsDisable, }).ToList(); //Use is UserReport Session["userReport"] = userModels; } catch (Exception ex) { SessionContext.Log(0, this.pageID, 0, MessageException.UserMessage.Gets, MessageException.Fail(ex.Message)); } return(Json(userModels, JsonRequestBehavior.AllowGet)); }
public JsonResult Get(long id) { DepartmentViewModel department = null; try { OrgUnit orgUnit = OrgUnit.Find(SessionContext, id); if (orgUnit == null) { SessionContext.Log(0, this.pageID, 0, MessageException.DepartmentMessage.Get, MessageException.Null("The static method Find return null, ID : " + id)); } department = new DepartmentViewModel { ID = orgUnit.ID, Code = orgUnit.Code, Name = orgUnit.CurrentName.Name.GetValue("th-TH"), Ministry = new MinistryViewModel { ID = orgUnit.OrganizationParent.ID, Code = orgUnit.OrganizationParent.Code, Name = orgUnit.OrganizationParent.CurrentName.Name.GetValue(SessionContext.CurrentLanguage.Code) } }; } catch (Exception ex) { SessionContext.Log(0, this.pageID, 0, MessageException.DepartmentMessage.Get, MessageException.Fail(ex.Message)); } return(Json(department, JsonRequestBehavior.AllowGet)); }
public JsonResult GetUser(long id = 0) { UserViewModel userViewModel = null; try { iSabaya.SelfAuthenticatedUser user = SessionContext.PersistenceSession.Get <iSabaya.SelfAuthenticatedUser>(id); if (user == null) { SessionContext.Log(0, this.pageID, 0, MessageException.AnnounceMessage.Get, MessageException.Null("Get SelfAuthenticatedUser return null, ID : " + id)); } else { userViewModel = new UserViewModel { Id = user.ID, IdCard = user.Person.OfficialIDNo, FirstNameTh = user.Person.CurrentName.FirstName.GetValue("th-TH"), LastNameTh = user.Person.CurrentName.LastName.GetValue("th-TH"), FirstNameEn = user.Person.CurrentName.FirstName.GetValue("en-US"), LastNameEn = user.Person.CurrentName.LastName.GetValue("en-US"), PhoneCenter = user.PhoneCenter == null ? "" : user.PhoneCenter + user.PhoneCenterTo, PhoneDirect = user.PhoneDirect == null ? "" : user.PhoneDirect, Mobile = user.MobilePhoneNumber == null ? "" : user.MobilePhoneNumber, Email = user.EMailAddress, Address = user.Address, Status = user.UserRoles[0].Role.Code == "User" ? user.UserRoles[0].Role.Description.Split(',')[0] : user.UserRoles[0].Role.Description, //IsOnline = false, IsDelete = user.IsEffective, Department = new DepartmentViewModel { ID = user.OrgUnit.ID, Name = user.OrgUnit.CurrentName.Name.GetValue("th-TH"), Code = user.OrgUnit.Code, Ministry = new MinistryViewModel { ID = user.OrgUnit.OrganizationParent.ID, Name = user.OrgUnit.OrganizationParent.CurrentName.Name.GetValue("th-TH"), Code = user.OrgUnit.OrganizationParent.Code, }, }, }; } } catch (Exception ex) { SessionContext.Log(0, this.pageID, 0, MessageException.UserMessage.Get, MessageException.Fail(ex.Message)); } return(Json(userViewModel, JsonRequestBehavior.AllowGet)); }
public JsonResult GetDepartments(long ministryId) { IList <DepartmentViewModel> departmentViewModels = null; try { IList <OrgUnit> orgUnits = SessionContext.PersistenceSession .QueryOver <OrgUnit>() .Where(x => x.OrganizationParent.ID == ministryId) .List(); departmentViewModels = orgUnits.Select(x => new DepartmentViewModel { ID = x.ID, Code = x.Code, Name = x.CurrentName.Name.GetValue("th-TH"), Ministry = new MinistryViewModel { ID = x.OrganizationParent.ID, Code = x.OrganizationParent.Code, Name = x.OrganizationParent.CurrentName.Name.GetValue(SessionContext.CurrentLanguage.Code) } }).ToList(); } catch (Exception ex) { SessionContext.Log(0, this.pageID, 0, MessageException.DepartmentMessage.Gets, MessageException.Fail(ex.Message)); } return(Json(departmentViewModels, JsonRequestBehavior.AllowGet)); }
public JsonResult Update(long id, string headLine, string content) { Announce announce = Announce.Get(SessionContext, id); if (announce == null) { SessionContext.Log(0, this.pageID, 0, MessageException.AnnounceMessage.Update, MessageException.Null("The static method Get return null, ID : " + id)); return(Json(new { Success = false, Message = MessageException.Error }, JsonRequestBehavior.AllowGet)); } using (ITransaction tx = SessionContext.PersistenceSession.BeginTransaction()) { try { announce.HeadLine = headLine; announce.Content = content; announce.UpdateAction = new iSabaya.UserAction(SessionContext.User); announce.EffectivePeriod = iSabaya.TimeInterval.EffectiveNow; announce.Persist(SessionContext); tx.Commit(); SessionContext.Log(0, this.pageID, 0, MessageException.AnnounceMessage.Update, MessageException.Success(id.ToString())); } catch (Exception ex) { tx.Rollback(); SessionContext.Log(0, this.pageID, 0, MessageException.AnnounceMessage.Update, MessageException.Fail(ex.Message)); return(Json(new { Success = false, Message = MessageException.Error }, JsonRequestBehavior.AllowGet)); } } return(Json(new { Success = true, Message = "แก้ไขประกาศ เรียบร้อย" }, JsonRequestBehavior.AllowGet)); }
public static string GetMessage(IMessageProvider messages, MessageException exception) { string result = GetMessage(messages, exception.MessageId, exception.Parameters); return(result ?? exception.Message); }
public JsonResult GetAnnounce(long id) { try { Announce announce = Announce.Get(SessionContext, id); if (announce == null) { SessionContext.Log(0, this.pageID, 0, MessageException.AnnounceMessage.Get, MessageException.Null("The static method Get return null, ID : " + id)); return(Json(new { Message = MessageException.Error }, JsonRequestBehavior.AllowGet)); } return(Json(new AnnounceViewModel { Id = announce.ID, HeadLine = announce.HeadLine, Content = announce.Content }, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { SessionContext.Log(0, this.pageID, 0, MessageException.AnnounceMessage.Get, MessageException.Fail(ex.Message)); return(Json(new { Message = MessageException.Error }, JsonRequestBehavior.AllowGet)); } }
private HttpResponseMessage Process(MessageException messageException, ExceptionHandlerContext context) { _logger.Error(messageException, $"{messageException.CustomMessage}"); return(context.Request.CreateErrorResponse(HttpStatusCode.BadRequest, messageException.Message)); }
public JsonResult Save(string headLine, string content) { if (string.IsNullOrEmpty(headLine) || string.IsNullOrEmpty(content)) { SessionContext.Log(0, this.pageID, 0, MessageException.AnnounceMessage.Save, MessageException.Null("The headLine or content is emptry.")); return(Json(new { Success = false, Message = MessageException.PleaseFillOut }, JsonRequestBehavior.AllowGet)); } using (ITransaction tx = SessionContext.PersistenceSession.BeginTransaction()) { try { Announce announce = new Announce { HeadLine = headLine, Content = content }; announce.CreateAction = new iSabaya.UserAction(SessionContext.User); announce.EffectivePeriod = iSabaya.TimeInterval.EffectiveNow; SessionContext.Persist(announce); tx.Commit(); SessionContext.Log(0, this.pageID, 0, MessageException.AnnounceMessage.Save, MessageException.Success()); } catch (Exception ex) { tx.Rollback(); SessionContext.Log(0, this.pageID, 0, MessageException.AnnounceMessage.Save, MessageException.Fail(ex.Message)); return(Json(new { Success = false, Message = MessageException.Error }, JsonRequestBehavior.AllowGet)); } } return(Json(new { Success = true, Message = "เพิ่มประกาศ เรียบร้อย" }, JsonRequestBehavior.AllowGet)); }
private void AllineaCategorie(List <category> listCategories) { using (UnitOfWork uof = new UnitOfWork()) { long rootCateg = listCategories.Where(a => a.is_root_category == 1).First().id.Value; //legge da db le categorie e i reparti foreach (var categDb in uof.CategorieRepository.Find(a => a.Codice > 0) .Select(a => new { a.Reparto, NomeCateg = a.Nome, a.ID }) .OrderBy(a => a.Reparto).OrderBy(a => a.NomeCateg).ToList()) { var categRepartoWebId = uof.RepartoWebRepository.Find(a => 1 == 1).Where(a => a.Reparto == categDb.Reparto).FirstOrDefault().CodiceWeb; /*verifico che esista il reparto tra le categorie web */ var repartoWeb = listCategories.Where(a => a.name.First().Value == categDb.Reparto && a.id_parent == rootCateg).DefaultIfEmpty(null).FirstOrDefault(); if (repartoWeb != null) { /*controllo che non esista già la categoria dentro al reparto nel ecomm*/ var existsCateg = listCategories.Where(a => a.id_parent == repartoWeb.id) .Where(a => a.name.First().Value == categDb.NomeCateg).FirstOrDefault(); if (existsCateg == null) { var newCateg = AggiungiCategoriaWeb(categRepartoWebId, categDb.NomeCateg); uof.CategorieWebRepository.Add(new Library.Entity.Ecomm.CategoriaWeb() { CategoriaID = categDb.ID, CodiceWeb = newCateg.id.Value }); uof.Commit(); ManagerLog.Logger.Info("Aggiunta categoria web: " + categDb.NomeCateg); } else { /*controlla che il codice web sia lo stesso*/ var categWebDb = uof.CategorieWebRepository.Find(a => a.CategoriaID == categDb.ID).FirstOrDefault(); if (categWebDb == null) { uof.CategorieWebRepository.Add(new Library.Entity.Ecomm.CategoriaWeb() { CategoriaID = categDb.ID, CodiceWeb = existsCateg.id.Value }); uof.Commit(); } else { categWebDb.CodiceWeb = existsCateg.id.Value; uof.CategorieWebRepository.Update(categWebDb); uof.Commit(); } } } else { var ex = new MessageException("Manca il reparto " + categDb.Reparto + " nel ecommerce"); ManagerLog.Logger.Error(ex.Message, ex); } } } }
/// <summary> /// Clients can call this method to commit the transaction. You should only use this method if /// you used the begin method to create the DataServiceTransaction. /// Otherwise, the gateway will commit or rollback the transaction as necessary. /// </summary> public void Commit() { if (_rollbackOnly) { Rollback(); return; } try { ProcessRefreshFills(); _pushMessages = new ArrayList(); for (int i = 0; i < _processedMessageBatches.Count; i++) { MessageBatch messageBatch = _processedMessageBatches[i] as MessageBatch; if (messageBatch.Messages != null && messageBatch.Messages.Count > 0) { DataDestination dataDestination = _dataService.GetDestination(messageBatch.IncomingMessage) as DataDestination; try { dataDestination.SequenceManager.ManageMessageBatch(messageBatch, this); } catch (Exception ex) { MessageException messageException = new MessageException(ex); ErrorMessage errorMessage = messageException.GetErrorMessage(); errorMessage.correlationId = messageBatch.IncomingMessage.messageId; errorMessage.destination = messageBatch.IncomingMessage.destination; messageBatch.Messages.Clear(); messageBatch.Messages.Add(errorMessage); } for (int j = 0; j < messageBatch.Messages.Count; j++) { IMessage message = messageBatch.Messages[j] as IMessage; if (!(message is ErrorMessage)) { _pushMessages.Add(message); } } } _outgoingMessages.AddRange(messageBatch.Messages); } for (int i = 0; i < _pushMessages.Count; i++) { IMessage message = _pushMessages[i] as IMessage; DataMessage dataMessage = message as DataMessage; if (dataMessage != null) { PushMessage(GetSubscribers(message), message); } } foreach (DictionaryEntry entry in _clientUpdateCollectionMessages) { UpdateCollectionMessage updateCollectionMessage = entry.Value as UpdateCollectionMessage; _outgoingMessages.Add(updateCollectionMessage); PushMessage(GetSubscribers(updateCollectionMessage), updateCollectionMessage); } foreach (DictionaryEntry entry in _updateCollectionMessages) { UpdateCollectionMessage updateCollectionMessage = entry.Value as UpdateCollectionMessage; _outgoingMessages.Add(updateCollectionMessage); PushMessage(GetSubscribers(updateCollectionMessage), updateCollectionMessage); } } finally { _transactionState = TransactionState.Committed; } }
public JsonResult Update(long id, string name) { try { if (string.IsNullOrEmpty(name)) { SessionContext.Log(0, this.pageID, 0, MessageException.StrategicMessage.Update, MessageException.Fail("The name is emptry.")); return(Json(new { Success = false, Message = MessageException.Error }, JsonRequestBehavior.AllowGet)); } Strategic strategic = Strategic.Get(SessionContext, id); if (strategic == null) { return(Json(new { Success = false, Message = MessageException.Error }, JsonRequestBehavior.AllowGet)); } using (ITransaction tx = SessionContext.PersistenceSession.BeginTransaction()) { try { strategic.Name = name; //strategic.EffectivePeriod.From = DateTime.Now; strategic.UpdateAction = new UserAction(SessionContext.User); strategic.EffectivePeriod = TimeInterval.EffectiveNow; strategic.Persist(SessionContext); tx.Commit(); SessionContext.Log(0, this.pageID, 0, MessageException.StrategicMessage.Update, MessageException.Success(id.ToString())); } catch (Exception ex) { tx.Rollback(); SessionContext.LogButNotFlush(0, this.pageID, 0, MessageException.StrategicMessage.Update, MessageException.Fail(ex.Message)); return(Json(new { Success = false, Message = MessageException.Error }, JsonRequestBehavior.AllowGet)); } } } catch (Exception ex) { SessionContext.LogButNotFlush(0, this.pageID, 0, MessageException.StrategicMessage.Update, MessageException.Fail(ex.Message)); return(Json(new { Success = false, Message = MessageException.Error }, JsonRequestBehavior.AllowGet)); } return(Json(new { Success = true, Message = "แก้ไขนโยบายเชิงยุทธศาสตร์ เรียบร้อย" }, JsonRequestBehavior.AllowGet)); }