public ActionResponse AddRequest(ProjectDeletionRequestModel model) { using (var unitWork = new UnitOfWork(context)) { ActionResponse response = new ActionResponse(); IMessageHelper mHelper; var project = unitWork.ProjectRepository.GetByID(model.ProjectId); if (project == null) { mHelper = new MessageHelper(); response.Success = false; response.Message = mHelper.GetNotFound("Project"); return(response); } var user = unitWork.UserRepository.GetWithInclude(u => u.Id == model.UserId, new string[] { "Organization" }).FirstOrDefault(); if (user == null) { mHelper = new MessageHelper(); response.Success = false; response.Message = mHelper.GetNotFound("User"); return(response); } var isRequestExists = unitWork.ProjectDeletionRepository.GetOne(p => p.ProjectId == project.Id); if (isRequestExists != null && isRequestExists.Status == ProjectDeletionStatus.Requested) { mHelper = new MessageHelper(); response.Success = false; response.Message = mHelper.GetProjectDeletionExistsMessage(); return(response); } if (isRequestExists != null && isRequestExists.Status == ProjectDeletionStatus.Approved) { mHelper = new MessageHelper(); response.Success = false; response.Message = mHelper.GetProjectDeletionApprovedMessage(); return(response); } if (isRequestExists != null && isRequestExists.Status == ProjectDeletionStatus.Cancelled) { isRequestExists.Status = ProjectDeletionStatus.Requested; isRequestExists.RequestedOn = DateTime.Now; isRequestExists.StatusUpdatedOn = DateTime.Now; isRequestExists.RequestedBy = user; unitWork.ProjectDeletionRepository.Update(isRequestExists); } else { unitWork.ProjectDeletionRepository.Insert(new EFProjectDeletionRequests() { Project = project, RequestedBy = user, RequestedOn = DateTime.Now, StatusUpdatedOn = DateTime.Now, Status = ProjectDeletionStatus.Requested }); } unitWork.Save(); var projectFunderIds = unitWork.ProjectFundersRepository.GetProjection(f => f.ProjectId == project.Id, f => f.FunderId); var projectImplementerIds = unitWork.ProjectImplementersRepository.GetProjection(i => i.ProjectId == project.Id, i => i.ImplementerId); var orgIds = projectFunderIds.Union(projectImplementerIds).ToList(); if (!orgIds.Contains(user.OrganizationId)) { orgIds.Add(user.OrganizationId); } var userEmails = unitWork.UserRepository.GetProjection(u => u.UserType == UserTypes.Standard && orgIds.Contains(u.OrganizationId) && u.Id != user.Id, u => u.Email); //var adminEmails = unitWork.UserRepository.GetProjection(u => u.UserType == UserTypes.Manager && u.Id != user.Id, u => u.Email); //var allEmails = userEmails.Union(adminEmails); List <EmailAddress> usersEmailList = new List <EmailAddress>(); foreach (var email in userEmails) { usersEmailList.Add(new EmailAddress() { Email = email }); } if (usersEmailList.Count > 0) { ISMTPSettingsService smtpService = new SMTPSettingsService(context); var smtpSettings = smtpService.GetPrivate(); SMTPSettingsModel smtpSettingsModel = new SMTPSettingsModel(); if (smtpSettings != null) { smtpSettingsModel.Host = smtpSettings.Host; smtpSettingsModel.Port = smtpSettings.Port; smtpSettingsModel.Username = smtpSettings.Username; smtpSettingsModel.Password = smtpSettings.Password; smtpSettingsModel.AdminEmail = smtpSettings.AdminEmail; smtpSettingsModel.SenderName = smtpSettings.SenderName; } string message = "", subject = "", footerMessage = ""; string projectTitle = "<h5>Project title: " + project.Title + "</h5>"; string requestedBy = "<h5>Requested by: " + user.Email + " (" + user.Organization.OrganizationName + ")</h5>"; var emailMessage = unitWork.EmailMessagesRepository.GetOne(m => m.MessageType == EmailMessageType.ProjectDeletionRequest); if (emailMessage != null) { subject = emailMessage.Subject; message = projectTitle + requestedBy + emailMessage.Message; footerMessage = emailMessage.FooterMessage; } IEmailHelper emailHelper = new EmailHelper(smtpSettingsModel.AdminEmail, smtpSettings.SenderName, smtpSettingsModel); emailHelper.SendEmailToUsers(usersEmailList, subject, "", message, footerMessage); } return(response); } }
public ActionResponse DeleteProject(int projectId, int userId) { using (var unitWork = new UnitOfWork(context)) { IMessageHelper mHelper; ActionResponse response = new ActionResponse(); var user = unitWork.UserRepository.GetOne(u => (u.UserType == UserTypes.Manager || u.UserType == UserTypes.SuperAdmin) && u.Id == userId); if (user == null) { mHelper = new MessageHelper(); response.Message = mHelper.GetInvalidAccountForProject(); response.Success = false; return(response); } var project = unitWork.ProjectRepository.GetByID(projectId); if (project == null) { mHelper = new MessageHelper(); response.Message = mHelper.GetNotFound("Project"); response.Success = false; return(response); } unitWork.ProjectRepository.Delete(project); unitWork.Save(); int userOrganizationId = 0; var deletionRequest = unitWork.ProjectDeletionRepository.GetWithInclude(p => p.ProjectId == projectId, new string[] { "RequestedBy" }).FirstOrDefault(); if (deletionRequest != null) { userOrganizationId = deletionRequest.RequestedBy.OrganizationId; } var projectFunderIds = unitWork.ProjectFundersRepository.GetProjection(f => f.ProjectId == project.Id, f => f.FunderId); var projectImplementerIds = unitWork.ProjectImplementersRepository.GetProjection(i => i.ProjectId == project.Id, i => i.ImplementerId); var orgIds = projectFunderIds.Union(projectImplementerIds).ToList(); if (!orgIds.Contains(userOrganizationId) && userOrganizationId != 0) { orgIds.Add(userOrganizationId); } var userEmails = unitWork.UserRepository.GetProjection(u => u.UserType == UserTypes.Standard && orgIds.Contains(u.OrganizationId), u => u.Email); var adminEmails = unitWork.UserRepository.GetProjection(u => u.UserType == UserTypes.Manager, u => u.Email); var allEmails = userEmails.Union(adminEmails); List <EmailAddress> usersEmailList = new List <EmailAddress>(); foreach (var email in allEmails) { usersEmailList.Add(new EmailAddress() { Email = email }); } if (usersEmailList.Count > 0) { ISMTPSettingsService smtpService = new SMTPSettingsService(context); var smtpSettings = smtpService.GetPrivate(); SMTPSettingsModel smtpSettingsModel = new SMTPSettingsModel(); if (smtpSettings != null) { smtpSettingsModel.Host = smtpSettings.Host; smtpSettingsModel.Port = smtpSettings.Port; smtpSettingsModel.Username = smtpSettings.Username; smtpSettingsModel.Password = smtpSettings.Password; smtpSettingsModel.AdminEmail = smtpSettings.AdminEmail; smtpSettingsModel.SenderName = smtpSettings.SenderName; } string message = "", subject = "", footerMessage = ""; var emailMessage = unitWork.EmailMessagesRepository.GetOne(m => m.MessageType == EmailMessageType.ProjectDeleted); if (emailMessage != null) { subject = emailMessage.Subject; message = emailMessage.Message; footerMessage = emailMessage.FooterMessage; } mHelper = new MessageHelper(); message += mHelper.ProjectDeletionMessage(project.Title); IEmailHelper emailHelper = new EmailHelper(smtpSettingsModel.AdminEmail, smtpSettings.SenderName, smtpSettingsModel); emailHelper.SendEmailToUsers(usersEmailList, subject, "", message, footerMessage); } return(response); } }
public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request) { ActionResponse response; bool isWaiting = request.DataStore.GetValue("IsWaiting") == null ? false : bool.Parse(request.DataStore.GetValue("IsWaiting")); int sqlIndex = int.Parse(request.DataStore.GetValue("SqlServerIndex")); string connectionString = request.DataStore.GetAllValues("SqlConnectionString")[sqlIndex]; // Must specify Initial Catalog string finishedActionName = request.DataStore.GetValue("FinishedActionName") == null ? null : request.DataStore.GetValue("FinishedActionName"); string targetSchema = request.DataStore.GetValue("TargetSchema"); // Specifies the schema used by the template string query = $"[{targetSchema}].sp_get_replication_counts"; DataTable recordCounts; try { recordCounts = SqlUtility.InvokeStoredProcedure(connectionString, query, null); } catch { // It's ok for this to fail, we'll just return an empty table recordCounts = new DataTable(); } bool isPullingData = false; if (isWaiting) { foreach (DataRow row in recordCounts.Rows) { isPullingData = Convert.ToInt64(row["Count"]) > 0; if (isPullingData) { break; } } response = isPullingData ? new ActionResponse(ActionStatus.Success, JsonUtility.GetEmptyJObject()) : new ActionResponse(ActionStatus.BatchNoState, JsonUtility.GetEmptyJObject()); } else { response = new ActionResponse(ActionStatus.Success, "{isFinished:false,status:" + JsonUtility.Serialize(recordCounts) + "}"); } if (string.IsNullOrEmpty(finishedActionName)) { return(response); } ActionResponse finishedResponse = await RequestUtility.CallAction(request, finishedActionName); var content = JObject.FromObject(finishedResponse.Body)["value"]?.ToString(); if ((isPullingData && finishedResponse.Status != ActionStatus.Failure) || finishedResponse.Status == ActionStatus.Success) { var resp = new ActionResponse(); if (!string.IsNullOrEmpty(content)) { resp = new ActionResponse(ActionStatus.Success, JsonUtility.GetJsonObjectFromJsonString( "{isFinished:true,FinishedActionName:\"" + finishedActionName + "\",TargetSchema:\"" + targetSchema + "\",status:" + JsonUtility.Serialize(recordCounts) + ", slices:" + JObject.FromObject(finishedResponse.Body)["value"]?.ToString() + "}")); } else { resp = new ActionResponse(ActionStatus.Success, JsonUtility.GetJsonObjectFromJsonString( "{isFinished:true, status:" + JsonUtility.Serialize(recordCounts) + "}")); } return(resp); } if (finishedResponse.Status == ActionStatus.BatchNoState || finishedResponse.Status == ActionStatus.BatchWithState) { var resp = new ActionResponse(); if (!string.IsNullOrEmpty(content)) { resp = new ActionResponse(ActionStatus.Success, JsonUtility.GetJsonObjectFromJsonString( "{isFinished:false,FinishedActionName:\"" + finishedActionName + "\",TargetSchema:\"" + targetSchema + "\",status:" + JsonUtility.Serialize(recordCounts) + ", slices:" + JObject.FromObject(finishedResponse.Body)["value"]?.ToString() + "}")); } else { resp = new ActionResponse(ActionStatus.Success, JsonUtility.GetJsonObjectFromJsonString( "{isFinished:false, status:" + JsonUtility.Serialize(recordCounts) + "}")); } return(resp); } return(finishedResponse); }
private void ValidateAction(ActionResponse actionResponse) { Assert.NotNull(actionResponse); }
public static EntitySet GetEntitySet(ActionResponse res, string resultName) { ActionResult rs = res.GetResult(resultName); EntitySet es = new EntitySet(); for (int i = 0; i < rs.Count; i++) { Entity o = new Entity(rs.GetDict(i)); es.Add(o); } return es; }
public ActionResponse UploadAppBanner() { int LanguageId = 1; Dictionary <Extensions.SystemInfo, string> setting = this.query.GetSystemSettings; ActionResponse response = new ActionResponse(); TemporaryImageLocation tmp = new TemporaryImageLocation(); try { HttpRequestMessage request = base.Request; HttpRequest httpRequest = HttpContext.Current.Request; NameValueCollection data = httpRequest.Form; if (data.Get("LocationID") == null) { response.success = false; response.code = HttpStatusCode.BadRequest.ToString(); response.message = "Location ID is required."; return(response); } HttpFileCollection data_files = httpRequest.Files; if (data_files.Get("Banner") == null) { response.success = false; response.code = HttpStatusCode.BadRequest.ToString(); response.message = "Banner is required."; return(response); } AspNetUser user = this.query.GetCurrentUserInfoByID(IdentityExtensions.GetUserId(base.User.Identity)); AppBanner banner = new AppBanner(); banner.AndroidEnabled = data.Get("AndroidEnabled") == null ? true : bool.Parse(data.Get("AndroidEnabled")); banner.BannerLocation = ""; banner.EntryTime = DateTime.Now; banner.IOSEnabled = data.Get("IOSEnabled") == null ? true : bool.Parse(data.Get("IOSEnabled")); banner.IsActive = true; banner.ModifiedBy = user.UserSequence; banner.ModifiedTime = DateTime.Now; banner.StoreID = int.Parse(data.Get("LocationID")); banner.UserID = user.UserSequence; foreach (object obj in data_files) { string fileName = (string)obj; if (fileName == "Banner" || fileName == "Logo") { HttpPostedFile file = httpRequest.Files[fileName]; string fileExt = Path.GetExtension(file.FileName).ToLower(); if (!(fileExt.ToLower() == ".jpg") && !(fileExt.ToLower() == ".png") && !(fileExt.ToLower() == ".jpeg")) { response.success = false; response.message = ((LanguageId == 1) ? "png, jgp, JPEG format are Allowed" : "png, jgp, JPEG الصيغ المسموح بها"); response.code = HttpStatusCode.BadRequest.ToString(); return(response); } this.query.SaveTxtLog("extention:" + fileExt); DirectoryInfo originalDirectory = new DirectoryInfo(string.Format("{0}{1}", HttpContext.Current.Server.MapPath("~\\"), setting[Extensions.SystemInfo.TempGalleryPath])); string pathString = originalDirectory.ToString(); string fileName2 = Path.GetFileName(file.FileName); string pre_fix = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss_"); string file_to_save = string.Format("{0}-{1}", pre_fix, fileName2); string file_to_save_thumbnail = string.Format("{0}-{1}", pre_fix + "logothumbnail", fileName2); string file_to_save_gallery = string.Format("{0}-{1}", pre_fix + "gallery", fileName2); string file_to_save_medium = string.Format("{0}-{1}", pre_fix + "med", fileName2); if (!Directory.Exists(pathString)) { Directory.CreateDirectory(pathString); } string path = string.Format("{0}\\{1}", pathString, file_to_save); this.query.SaveTxtLog("path:" + path); string new_path_thumbnail = string.Format("{0}\\{1}", pathString, file_to_save_thumbnail); string new_path_gallery = string.Format("{0}\\{1}", pathString, file_to_save_gallery); string new_path_medium = string.Format("{0}\\{1}", pathString, file_to_save_medium); file.SaveAs(path); this.query.SaveTxtLog("save as:"); new ImageJob(file, new_path_thumbnail, new Instructions("mode=pad;format=jpg;width=" + 1027.ToString() + ";height=" + 530.ToString())) { CreateParentDirectory = true }.Build(); string MediumSize = string.Concat(new string[] { "mode=pad;format=jpg;width=", 513.ToString(), ";height=", 265.ToString(), ";" }); new ImageJob(file, new_path_medium, new Instructions(MediumSize)) { CreateParentDirectory = true }.Build(); tmp.OrignalFileLocation = file_to_save; tmp.ThumbnailLocation = file_to_save_thumbnail; tmp.MediamFileLocation = file_to_save_medium; tmp.EntryTime = DateTime.Now; this.db.TemporaryImageLocations.Add(tmp); this.db.SaveChanges(); string x = this.ReplaceImage(tmp.ID); banner.BannerLocation = file_to_save; this.query.SaveTxtLog("saved"); response.success = true; response.code = HttpStatusCode.OK.ToString(); } } response.success = true; response.message = "Banner Saved"; response.code = HttpStatusCode.OK.ToString(); this.db.AppBanners.Add(banner); this.db.SaveChanges(); } catch (Exception ex) { this.query.SaveTxtLog("Expection (UploadTemp):" + ex.ToString()); response.code = HttpStatusCode.ExpectationFailed.ToString(); response.success = false; response.message = "Error Creating Shop Error-Code:20EXPD"; } return(response); }
public void Add(ActionRequest req, ActionResponse res) { string msg = ""; try { //权限判断一,需要登录(用户或管理员) if (!Session.IsLogin) { res.Error(VERIFY_ERROR); return; } //权限判断二,必须是管理员 /* if (!Session.IsAdmin) { res.Error(VERIFY_ERROR); return; } */ ObModelInfo ei = null; //解析请求参数,转换为实体类(针对单一实体结构) ei = req.GetModelByNameOrFirst<ObModelInfo>(ENTITY_REQ); //解析请求参数(针对有规律的实体结构(同前缀的同构表)) /**** ActReqParam param = req.GetParamByNameOrFirst(ENTITY_REQ); if (param == null) { res.Error("参数" + ENTITY_REQ + "错误"); return; } //定义参数(对于DateTime类型,以"yyyy-MM-dd HH:mm:ss"格式的字符串处理) long obId = 0; int obLevel = 0; string obName = ""; string obDescri = ""; bool obEnabled = false; decimal obMoney = 0.0m; double obScore = 0.0d; long userId = 0; //验证参数(参数名必须和ObModel实体ObModelInfo的属性别名一致) if (!param.TryGetFirstLong("obId", out obId)) { res.Error("参数" + ENTITY_REQ + "的属性obId错误"); return; } if (!param.TryGetFirstInt("obLevel", out obLevel)) { res.Error("参数" + ENTITY_REQ + "的属性obLevel错误"); return; } if (!param.TryGetFirstString("obName", out obName)) { res.Error("参数" + ENTITY_REQ + "的属性obName错误"); return; } if (!param.TryGetFirstString("obDescri", out obDescri)) { res.Error("参数" + ENTITY_REQ + "的属性obDescri错误"); return; } if (!param.TryGetFirstBool("obEnabled", out obEnabled)) { res.Error("参数" + ENTITY_REQ + "的属性obEnabled错误"); return; } if (!param.TryGetFirstDecimal("obMoney", out obMoney)) { res.Error("参数" + ENTITY_REQ + "的属性obMoney错误"); return; } if (!param.TryGetFirstDouble("obScore", out obScore)) { res.Error("参数" + ENTITY_REQ + "的属性obScore错误"); return; } if (!param.TryGetFirstLong("userId", out userId)) { res.Error("参数" + ENTITY_REQ + "的属性userId错误"); return; } //设置实体参数值 long uid = userId % 1024; string tableNameFormat = @"TbObModel_{0}"; //同前缀的同构表名格式定义 string tableName = String.Format(tableNameFormat, uid); ei = new ObModelInfo(tableName); ei.ObLevel.Set(obLevel); ei.ObName.Set(obName); ei.ObDescri.Set(obDescri); ei.ObEnabled.Set(obEnabled); ei.ObMoney.Set(obMoney); ei.ObScore.Set(obScore); ei.UserId.Set(userId); ****/ //调用业务处理方法 ei = AddEntity(ei, out msg); if (ei == null) { res.Error(msg); return; } //返回结果集 ActionResult ar = res.AddResult(ENTITY_RES, ENTITY_FIELDS); //定义返回结果集名称和字段名 ar.AddModel(ei); //添加结果集到ActionResult } catch (Exception ex) { msg = "ys.ObModel.add 接口调用异常"; Logger.Error(ex, msg); res.Error(msg); } }
internal void LogRequest(string request, TimeSpan duration, bool sucess, ActionRequest requestBody, ActionResponse responseToReturn) { if (responseToReturn == null) { responseToReturn = new ActionResponse(ActionStatus.Failure); } string respone = responseToReturn.Status.ResponseCode(); // Add the request/response onto body string traceId = Guid.NewGuid().ToString(); this.AddTraceId(traceId); this.LogTrace("RequestBody", requestBody, traceId); this.LogTrace("ResponseBody", responseToReturn, traceId); this.telemetryClient.TrackRequest(request, DateTimeOffset.Now, duration, respone, sucess); this.ClearTraceId(); }
public void List(ActionRequest req, ActionResponse res) { string msg = ""; ListAttrInfo la; try { if (!Session.IsAdmin) //权限判断,是管理员 { res.Error(VERIFY_ERROR); return; } ObModelQuery qry = req.GetModelByNameOrFirst<ObModelQuery>(QUERY); List<ObModelInfo> list = GetList(qry, out la, out msg); if (list == null) { res.Error(msg); return; } ActionResult ar = res.AddResult(ENTITY_RES, ENTITY_FIELDS); ar.AddModels<ObModelInfo>(list); ActionResult arAttr = res.AddResult(LISTATTR, LISTATTR_FIELDS); arAttr.AddModel(la); //获取关联结果集 if (qry.GetRelation.IsTrue()) { ActionResult arRe = res.AddResult(RELATION_RES, RELATION_FIELDS); if (list.Count > 0) { //获取ObModel的obId串 List<long> obIds = new List<long>(); for(int i=0,j=list.Count;i<j;i++) { obIds.Add(list[i].ObId.Value); } //调用ObRelation实体对应的BL类中的获取列表方法 // ObRelationInfo 中属性 ObId 对应 ObModelInfo 的 ObId // RelationQuery 中属性 ObIds 对应 ObModelInfo 的 ObId (多个) /* RelationBL rbl = new RelationBL(); RelationQuery rqry = new RelationQuery(); ListAttrInfo rla = new ListAttrInfo(); rqry.PageNo = 1; rqry.PageSize = list.Count; // rqry.ObIds.Set(obIds); List<ObRelationInfo> rList = rbl.GetList(rqry, out rla, out msg); arRe.AddModels<ObRelationInfo>(rList); */ } else { arRe.AddModels<ObRelationInfo>(new List<ObRelationInfo>()); } } } catch (Exception ex) { msg = "ys.obModel.list 接口调用异常"; Logger.Error(ex, msg); res.Error(msg); } }
public void Update(ActionRequest req, ActionResponse res) { string msg = ""; try { //权限判断一,需要登录(用户或管理员) if (!Session.IsLogin) { res.Error(VERIFY_ERROR); return; } YsMemberInfo user = Session.User; //获取登录用户信息 //权限判断二,必须是管理员 /* if (!Session.IsAdmin) { res.Error(VERIFY_ERROR); return; } */ ObModelInfo ei = null; //解析请求参数,转换为实体类 ei = req.GetModelByNameOrFirst<ObModelInfo>(ENTITY_REQ); //解析请求参数(针对有规律的实体结构(同前缀的同构表)) //参照 : public void Add(ActionRequest req, ActionResponse res) 方法 //调用业务处理方法一(用户无关) ei = UpdateEntity(ei, out msg); /* //调用业务处理方法二(用户相关,操作权限判断) ei = UpdateEntity(ei, user, out msg); */ if (ei == null) { res.Error(msg); return; } //返回结果集 ActionResult ar = res.AddResult(ENTITY_RES, ENTITY_FIELDS); //定义返回结果集名称和字段名 ar.AddModel(ei); //添加结果集到ActionResult } catch (Exception ex) { msg = "ys.ObModel.update 接口调用异常"; Logger.Error(ex, msg); res.Error(msg); } }
public void Get(ActionRequest req, ActionResponse res) { string msg = ""; try { //权限判断,是否有登录(根据业务确定是否需要此判断) /* if (!Session.IsLogin) // (!Session.IsAdmin) { res.Error(VERIFY_ERROR); return; } */ ActReqParam param; if (!req.TryGetParam(ENTITY_REQ, out param)) { res.Error("参数" + ENTITY_REQ + "错误"); return; } long obId = 0; if (!param.TryGetFirstLong("obId", out obId)) { res.Error("参数" + ENTITY_REQ + "属性obId错误"); return; } //用户相关 /* long userId = 0; if (!param.TryGetFirstLong("userId", out userId)) { res.Error("参数" + ENTITY_REQ + "的属性userId错误"); } */ ObModelInfo ei = null; ei = GetEntity(obId, out msg); //ei = GetEntity(obId, userId, out msg); //用户相关 if (ei == null) { res.Error(msg); return; } ActionResult ar = res.AddResult(ENTITY_RES, ENTITY_FIELDS); ar.AddModel(ei); } catch (Exception ex) { msg = "ext.ObModel.get 接口调用异常"; Logger.Error(ex, msg); res.Error(msg); } }
public void Delete(ActionRequest req, ActionResponse res) { string msg = ""; try { //权限判断,是否有登录(根据业务确定是否 限制为管理员) if (!Session.IsLogin) // (!Session.IsAdmin) { res.Error(VERIFY_ERROR); return; } ActReqParam param; if (!req.TryGetParam(ENTITY_REQ, out param)) { res.Error("参数" + ENTITY_REQ + "错误"); return; } int obId = 0; if (!param.TryGetInt(0, "obId", out obId)) { res.Error("参数" + ENTITY_REQ + "属性obId错误"); return; } //用户相关 /* long userId = 0; if (!param.TryGetLong(0, "userId", out userId)) { res.Error("参数" + ENTITY_REQ + "的属性userId错误"); } */ int code = 0; code = DeleteEntity(obId, out msg); //code = DeleteEntity(obId, userId, out msg); //用户相关 ActionResult ar = res.AddResult(RESULT, RESULT_FIELDS); ar.AddValues(code, msg); } catch (Exception ex) { msg = "ext.obModel.delete 接口调用异常"; Logger.Error(ex, msg); res.Error(msg); } }
private ActionResponse CreateResponse(Gamer oldGamer, Gamer newGamer) { var response = new ActionResponse(); response.Success = true; response.AchievementChanges.Add(GetAchievementsDiff(oldGamer.Achievements, newGamer.Achievements, ChangeAction.Unassign)); response.AchievementChanges.Add(GetAchievementsDiff(newGamer.Achievements, oldGamer.Achievements, ChangeAction.Assign)); response.StatusChanges.Add(GetStatusDiff(oldGamer.GamerStatuses, newGamer.GamerStatuses, ChangeAction.Unassign)); response.StatusChanges.Add(GetStatusDiff(newGamer.GamerStatuses, oldGamer.GamerStatuses, ChangeAction.Assign)); if (oldGamer.CurrentLevel != newGamer.CurrentLevel) { var levelDiff = Math.Abs(oldGamer.CurrentLevel.LevelNumber - newGamer.CurrentLevel.LevelNumber); response.LevelChange = new NumericCharacteristicChange(levelDiff, oldGamer.CurrentLevel > newGamer.CurrentLevel ? NumberOperation.Decrease : NumberOperation.Increase); } if (oldGamer.Points != newGamer.Points) { var pointsDiff = Math.Abs(oldGamer.Points - newGamer.Points); response.PointsChange = new NumericCharacteristicChange(pointsDiff, oldGamer.Points > newGamer.Points ? NumberOperation.Decrease : NumberOperation.Increase); } return response; }
public async Task <ActionResponse> ImportEnvelopeData(List <ImportedEnvelopeData> envelopeList) { using (var unitWork = new UnitOfWork(context)) { ActionResponse response = new ActionResponse(); var organizations = unitWork.OrganizationRepository.GetManyQueryable(o => o.Id != 0); var defaultOrganizationType = unitWork.OrganizationTypesRepository.GetOne(o => o.TypeName == "Other"); var envelopeTypes = unitWork.EnvelopeTypesRepository.GetManyQueryable(e => e.Id != 0); var financialYears = unitWork.FinancialYearRepository.GetManyQueryable(f => f.Id != 0); if (defaultOrganizationType == null) { defaultOrganizationType = unitWork.OrganizationTypesRepository.Insert(new EFOrganizationTypes() { TypeName = "Other" }); unitWork.Save(); } var envelopeDevelopment = (from et in envelopeTypes where et.TypeName.Equals("Development", StringComparison.OrdinalIgnoreCase) select et).FirstOrDefault(); var envelopeHumanitarian = (from et in envelopeTypes where et.TypeName.Equals("Humanitarian", StringComparison.OrdinalIgnoreCase) select et).FirstOrDefault(); if (envelopeDevelopment == null) { envelopeDevelopment = unitWork.EnvelopeTypesRepository.Insert(new EFEnvelopeTypes() { TypeName = "Development" }); unitWork.Save(); } if (envelopeHumanitarian == null) { envelopeHumanitarian = unitWork.EnvelopeTypesRepository.Insert(new EFEnvelopeTypes() { TypeName = "Humanatarian" }); } var yearEighteen = (from fy in financialYears where fy.FinancialYear == 2018 select fy).FirstOrDefault(); var yearNineteen = (from fy in financialYears where fy.FinancialYear == 2019 select fy).FirstOrDefault(); var yearTwenty = (from fy in financialYears where fy.FinancialYear == 2020 select fy).FirstOrDefault(); if (yearEighteen == null) { yearEighteen = unitWork.FinancialYearRepository.Insert(new EFFinancialYears() { FinancialYear = 2018 }); unitWork.Save(); } if (yearNineteen == null) { yearNineteen = unitWork.FinancialYearRepository.Insert(new EFFinancialYears() { FinancialYear = 2019 }); unitWork.Save(); } if (yearTwenty == null) { yearTwenty = unitWork.FinancialYearRepository.Insert(new EFFinancialYears() { FinancialYear = 2020 }); unitWork.Save(); } try { var strategy = context.Database.CreateExecutionStrategy(); await strategy.ExecuteAsync(async() => { using (var transaction = context.Database.BeginTransaction()) { foreach (var envelope in envelopeList) { EFOrganization organization = null; if (!string.IsNullOrEmpty(envelope.Organization)) { organization = (from o in organizations where o.OrganizationName.Equals(envelope.Organization, StringComparison.OrdinalIgnoreCase) select o).FirstOrDefault(); if (organization == null) { if (defaultOrganizationType != null) { organization = unitWork.OrganizationRepository.Insert(new EFOrganization() { OrganizationType = defaultOrganizationType, OrganizationName = envelope.Organization }); unitWork.Save(); } } EFEnvelope newEnvelope = null; if (organization != null) { newEnvelope = unitWork.EnvelopeRepository.Insert(new EFEnvelope() { Funder = organization, Currency = envelope.Currency, ExchangeRate = envelope.ExchangeRate }); unitWork.Save(); } unitWork.EnvelopeYearlyBreakupRepository.Insert(new EFEnvelopeYearlyBreakup() { Envelope = newEnvelope, Year = yearEighteen, EnvelopeType = envelopeDevelopment, Amount = envelope.DevelopmentEighteen }); unitWork.EnvelopeYearlyBreakupRepository.Insert(new EFEnvelopeYearlyBreakup() { Envelope = newEnvelope, Year = yearNineteen, EnvelopeType = envelopeDevelopment, Amount = envelope.DevelopmentNineteen }); unitWork.EnvelopeYearlyBreakupRepository.Insert(new EFEnvelopeYearlyBreakup() { Envelope = newEnvelope, Year = yearTwenty, EnvelopeType = envelopeDevelopment, Amount = envelope.DevelopmentTwenty }); unitWork.EnvelopeYearlyBreakupRepository.Insert(new EFEnvelopeYearlyBreakup() { Envelope = newEnvelope, Year = yearEighteen, EnvelopeType = envelopeHumanitarian, Amount = envelope.HumanitarianEighteen }); unitWork.EnvelopeYearlyBreakupRepository.Insert(new EFEnvelopeYearlyBreakup() { Envelope = newEnvelope, Year = yearNineteen, EnvelopeType = envelopeHumanitarian, Amount = envelope.HumanitarianNineteen }); unitWork.EnvelopeYearlyBreakupRepository.Insert(new EFEnvelopeYearlyBreakup() { Envelope = newEnvelope, Year = yearTwenty, EnvelopeType = envelopeHumanitarian, Amount = envelope.HumanitarianTwenty }); await unitWork.SaveAsync(); } } transaction.Commit(); } }); } catch (Exception ex) { response.Success = false; response.Message = ex.Message; } return(await Task <ActionResponse> .Run(() => response).ConfigureAwait(false)); } }
public ActionResponse Execute() { var response = new ActionResponse { Action = _node }; using (var cn = _cf.GetConnection()) { try { cn.Open(); } catch (DbException e) { _context.Error($"Can't open {_cf.AdoProvider} connection specified in {_node.Type} action."); response.Message = e.Message; response.Code = 500; return(response); } try { if (_node.Command == string.Empty) { var logger = new Cfg.Net.Loggers.MemoryLogger(); _node.Command = _commandReader.Read(_node.Url == string.Empty ? _node.File : _node.Url, new Dictionary <string, string>(), logger); foreach (var warning in logger.Warnings()) { _context.Warn(warning); } foreach (var error in logger.Errors()) { _context.Error(error); } } if (_node.Command.Contains("@")) { var parameters = new ExpandoObject(); var editor = (IDictionary <string, object>)parameters; foreach (var parameter in _context.Process.Parameters) { if (parameter.Name.Contains(".")) { parameter.Name = parameter.Name.Replace(".", "_"); } } foreach (var name in new AdoParameterFinder().Find(_node.Command).Distinct().ToList()) { var match = _context.Process.Parameters.FirstOrDefault(p => p.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); if (match != null) { editor[match.Name] = match.Convert(match.Value); } } _node.RowCount = cn.Execute(_node.Command, parameters, commandTimeout: _node.TimeOut); } else { _node.RowCount = cn.Execute(_node.Command, commandTimeout: _node.TimeOut); } var message = $"{(_node.Description == string.Empty ? _node.Type + " action" : "'" + _node.Description + "'")} affected {(_node.RowCount == -1 ? 0 : _node.RowCount)} row{_node.RowCount.Plural()}."; response.Message = message; _context.Info(message); } catch (DbException ex) { response.Code = 500; response.Message = ex.Message + Environment.NewLine + _node.Command.Replace("{", "{{").Replace("}", "}}"); } } return(response); }
public ActionResult BranchDistributorAgentEdit(int?id, AgentModel model, FormCollection fc) { model.AgentId = id == null ? 0 : id.Value; model.UpdatedBy = LogedUserId; model.UpdatedDate = CurrentDate; model.EmailId = model.EmailId.Trim(';'); _model = _rep.Detail(id, out _res); if (_rep.CheckEditDuplicateEmail(model.Email, id.Value)) { TempData["ActionResponse"] = "Registration failed! Email already exists, please re-enter and try again"; foreach (var AsociatedProductOfAgent in _model.AgentProductList) { ViewData[AsociatedProductOfAgent.ProductName] = new SelectList(_rep.GetAllRolesListonProductWise(AsociatedProductOfAgent.ProductId), "RoleName", "RoleName", ""); } ViewData["AgentBank"] = _agentdetailsprovider.GetAgentBankList(id.Value); ViewData["Countrylist"] = new SelectList(_rep.GetCountry(), "CountryId", "CountryName", _rep.GetCountryInfo(_model.NativeCountryId)); ViewData["AgentZone"] = new SelectList(_rep.GetZoneList(), "ZoneId", "ZoneName", _model.ZoneId); ViewData["AgentDistrict"] = new SelectList(_rep.GetDistrictListbyZoneId(Convert.ToInt32(_model.ZoneId)), "DistrictId", "DistrictName", Convert.ToInt32(_model.DistrictId)); ViewData["Status"] = new SelectList(_rep.GetStatus(), "id", "Name", 1); ViewData["AgentTypes"] = new SelectList(_rep.GetAgentType(), "AgentTypeId", "AgentTypeName"); ViewData["agentClass"] = new SelectList(_rep.GetAgentClass(), "AgentClassId", "AgentClassName"); ViewData["Banks"] = new SelectList(_rep.GetbankInformation(), "BankId", "BankName"); ViewData["BankBranches"] = new SelectList(_rep.GetbankBranchInformation(), "BankBranchId", "BranchName"); ViewData["BankAccountTypes"] = new SelectList(_rep.GetbankAccountType(), "BankAccountTypeId", "AccountTypeName"); ViewData["TimeZones"] = new SelectList(_rep.GetTimeZoneList(), "RecordID", "DisplayName"); return(View(_model)); } else { if (!string.IsNullOrEmpty(model.MobileNo) && !_rep.CheckEditDuplicateMobileNumber(model.MobileNo, id.Value)) { TempData["ActionResponse"] = "Registration failed! Mobile Number already exists, please re-enter and try again"; foreach (var AsociatedProductOfAgent in _model.AgentProductList) { ViewData[AsociatedProductOfAgent.ProductName] = new SelectList(_rep.GetAllRolesListonProductWise(AsociatedProductOfAgent.ProductId), "RoleName", "RoleName", ""); } ViewData["AgentBank"] = _agentdetailsprovider.GetAgentBankList(id.Value); ViewData["Countrylist"] = new SelectList(_rep.GetCountry(), "CountryId", "CountryName", _rep.GetCountryInfo(_model.NativeCountryId)); ViewData["AgentZone"] = new SelectList(_rep.GetZoneList(), "ZoneId", "ZoneName", _model.ZoneId); ViewData["AgentDistrict"] = new SelectList(_rep.GetDistrictListbyZoneId(Convert.ToInt32(_model.ZoneId)), "DistrictId", "DistrictName", Convert.ToInt32(_model.DistrictId)); ViewData["Status"] = new SelectList(_rep.GetStatus(), "id", "Name", 1); ViewData["AgentTypes"] = new SelectList(_rep.GetAgentType(), "AgentTypeId", "AgentTypeName"); ViewData["agentClass"] = new SelectList(_rep.GetAgentClass(), "AgentClassId", "AgentClassName"); ViewData["Banks"] = new SelectList(_rep.GetbankInformation(), "BankId", "BankName"); ViewData["BankBranches"] = new SelectList(_rep.GetbankBranchInformation(), "BankBranchId", "BranchName"); ViewData["BankAccountTypes"] = new SelectList(_rep.GetbankAccountType(), "BankAccountTypeId", "AccountTypeName"); ViewData["TimeZones"] = new SelectList(_rep.GetTimeZoneList(), "RecordID", "DisplayName"); return(View(_model)); } else { int[] ChkProductId = new int[1] { 1 }; _res = _rep.Edit(id, model, ChkProductId, fc); TempData["InfoMessage"] = _res.ActionMessage; if (_res.ErrNumber == 0) { return(RedirectToAction("AgentList", "BranchDistributorManagement", new { id = model.DistributorId })); } else { _model = _rep.Detail(id, out _res); TempData["InfoMessage"] = _res.ActionMessage; if (_res.ErrNumber == 0) { foreach (var AsociatedProductOfAgent in _model.AgentProductList) { ViewData[AsociatedProductOfAgent.ProductName] = new SelectList(_rep.GetAllRolesListonProductWise(AsociatedProductOfAgent.ProductId), "RoleName", "RoleName", ""); } ViewData["AgentBank"] = _agentdetailsprovider.GetAgentBankList(id.Value); ViewData["Countrylist"] = new SelectList(_rep.GetCountry(), "CountryId", "CountryName", _rep.GetCountryInfo(_model.NativeCountryId)); ViewData["AgentZone"] = new SelectList(_rep.GetZoneList(), "ZoneId", "ZoneName", _model.ZoneId); ViewData["AgentDistrict"] = new SelectList(_rep.GetDistrictListbyZoneId(Convert.ToInt32(_model.ZoneId)), "DistrictId", "DistrictName", Convert.ToInt32(_model.DistrictId)); ViewData["Status"] = new SelectList(_rep.GetStatus(), "id", "Name", 1); ViewData["AgentTypes"] = new SelectList(_rep.GetAgentType(), "AgentTypeId", "AgentTypeName"); ViewData["agentClass"] = new SelectList(_rep.GetAgentClass(), "AgentClassId", "AgentClassName"); ViewData["Banks"] = new SelectList(_rep.GetbankInformation(), "BankId", "BankName"); ViewData["BankBranches"] = new SelectList(_rep.GetbankBranchInformation(), "BankBranchId", "BranchName"); ViewData["BankAccountTypes"] = new SelectList(_rep.GetbankAccountType(), "BankAccountTypeId", "AccountTypeName"); ViewData["TimeZones"] = new SelectList(_rep.GetTimeZoneList(), "RecordID", "DisplayName"); return(View(_model)); } else { return(RedirectToAction("DistributorAgentList")); } } } } }
private void HandleOnActionResponseReceived(string sender, string response) { ActionResponse ar = JsonUtility.FromJson <ActionResponse> (response); if (playerID.Equals(ar.Player_Name)) { buyinChips = ar.Player_BuyIn_Chips; totalRealMoney = ar.Player_Total_Real_Chips; totalChips = ar.Player_Total_Play_Chips; DisplayTotalChips(); betAmount += ar.Bet_Amount; DisplayBetAmount(); if (ar.Bet_Amount > 0) { DisplayChipOnPlayerAction(ar); } if (ar.Action == (int)PLAYER_ACTION.ACTION_WA_UP) { DisplayUpWhoopAssCard(); } else if (ar.Action == (int)PLAYER_ACTION.ACTION_WA_DOWN) { DisplayDownWhoopAssCard(); } if (ar.Action == (int)PLAYER_ACTION.CHECK) { SoundManager.Instance.PlayCheckActionSound(Camera.main.transform.position); } // Display dealer WA card if (ar.Action == (int)PLAYER_ACTION.ACTION_WA_UP || ar.Action == (int)PLAYER_ACTION.ACTION_WA_DOWN || ar.Action == (int)PLAYER_ACTION.ACTION_WA_NO) { if (playerID.Equals(NetworkManager.Instance.playerID)) { GameManager.Instance.dealerWhoopAssCard.gameObject.SetActive(true); } SoundManager.Instance.PlayBetCallSound(Camera.main.transform.position); } if (ar.Action == (int)PLAYER_ACTION.TIMEOUT) { GetComponent <CanvasGroup> ().alpha = .4f; playerInfo.Player_Status = (int)PLAYER_ACTION.TIMEOUT; SoundManager.Instance.PlayFoldActionSound(Camera.main.transform.position); playerFoldParent.SetActive(true); } else if (ar.Action == (int)PLAYER_ACTION.FOLD) { GetComponent <CanvasGroup> ().alpha = .4f; playerInfo.Player_Status = (int)PLAYER_ACTION.FOLD; SoundManager.Instance.PlayFoldActionSound(Camera.main.transform.position); playerFoldParent.SetActive(true); } else if (ar.Action == (int)PLAYER_ACTION.ALLIN) { playerInfo.Player_Status = (int)PLAYER_ACTION.ALLIN; SoundManager.Instance.PlayAllinActionSound(Camera.main.transform.position); } // playerInfo.Player_Status = ar.Action; HistoryManager.GetInstance().AddHistory(playerID, "name", RoundController.GetInstance().currentTableGameRound, ar.Bet_Amount, betAmount, GetPlayerAction(ar.Action), ar.IsBetOnStraight); } }
internal void LogEvent(string eventName, Dictionary <string, string> properties, ActionRequest requestBody, ActionResponse responseToReturn) { // Add the reqyest/response onto body if (properties == null) { properties = new Dictionary <string, string>(); } string traceId = Guid.NewGuid().ToString(); this.AddTraceId(traceId); this.LogTrace("RequestBody", requestBody, traceId); this.LogTrace("ResponseBody", responseToReturn, traceId); this.telemetryClient.TrackEvent(eventName, properties); this.Flush(); this.ClearTraceId(); }
/// <summary> /// Handles the NavigationAction event of the navigation addon. /// </summary> void OnNavigationAction(object sender, NavigationActionEventArgs args) { try { Logger.LogTrace("MainForm handling OnNavigationAction ..."); Application.UseWaitCursor = true; this.SuspendLayoutEx(); bool isVoidAction = false; bool isPreviewAction = false; ActionRequest request = new ActionRequest(); ActionResponse response = null; Logger.LogTrace("Action is of type: " + args.ActionType.ToString()); pnlPreview.SuspendLayoutEx(); pnlProperties.SuspendLayoutEx(); lblNoPreview.Text = Translator.Translate("TXT_THEREARENOITEMS"); prepareAutoPreview = (args.ActionType == NavActionType.ActionPrepareAutoPreview && args.ActionType != NavActionType.ActionCancelAutoPreview); switch (args.ActionType) { case NavActionType.ActionSaveProperties: // It is a save property request. request.ActionType = ActionManagement.ActionType.ActionSaveProperties; request.Items = args.Paths; // don't matter any way break; case NavActionType.ActionSelectDirectory: case NavActionType.ActionSelectFile: case NavActionType.ActionSelectMultipleItems: // It is a property request. request.ActionType = ActionManagement.ActionType.ActionBeginEdit; request.Items = args.Paths; break; case NavActionType.ActionDoubleClickFile: // It is a regular preview request. request.ActionType = ActionManagement.ActionType.ActionBeginPreview; request.Items = args.Paths; isPreviewAction = true; break; case NavActionType.ActionNotifyNonPreviewableItem: lblNoPreview.Text = Translator.Translate("TXT_NOTIFY_NON_PREVIEW"); isPreviewAction = true; break; case NavActionType.ActionNotifyPreviewableItem: lblNoPreview.Text = Translator.Translate("TXT_NOTIFY_PREVIEW"); isPreviewAction = true; break; case NavActionType.ActionPrepareAutoPreview: lblNoPreview.Text = Translator.Translate("TXT_PREPARE_PREVIEW"); prepareAutoPreview = true; isPreviewAction = true; break; case NavActionType.ActionCancelAutoPreview: if (args.AdditionalData == null && prepareAutoPreview) { lblNoPreview.Text = Translator.Translate("TXT_PREVIEW_CANCELED"); } else { lblNoPreview.Text = Translator.Translate("TXT_NOTIFY_PREVIEW"); } isPreviewAction = true; break; case NavActionType.ActionReloadNavigation: { // Don't reselct addons, send command to the ones already selected. isVoidAction = true; NavBaseCtl ctl = GetNavigationControl(); if (ctl != null) { ctl.Reload(args.AdditionalData); } } break; case NavActionType.ActionReloadPreview: { // Don't reselct addons, send command to the ones already selected. isVoidAction = true; PreviewBaseCtl ctl = GetPreviewControl(); if (ctl != null) { ctl.Reload(args.AdditionalData); } } break; case NavActionType.ActionReloadProperties: { // Don't reselct addons, send command to the ones already selected. isVoidAction = true; PropBaseCtl ctl = GetPropertiesControl(); if (ctl != null) { ctl.Reload(args.AdditionalData); } } break; case NavActionType.ActionDoubleClickDirectory: default: // No actions currently taken in this situation. isVoidAction = true; break; } if (!isVoidAction) { response = AddonsCore.Instance.DispatchAction(request); bool failed = ActionResponse.IsFailedAction(response); if (isPreviewAction) { PreviewBaseCtl previewCtl = GetPreviewControl(); if (previewCtl != null) { previewCtl.EndPreview(); previewCtl.NavigationAction -= new BaseAddonCtl.NavigationActionEventHandler(OnNavigationAction); } if (failed) { Logger.LogTrace("Preview action has failed."); if (!pnlPreview.Controls.Contains(lblNoPreview)) { pnlPreview.Controls.Clear(); pnlPreview.Controls.Add(lblNoPreview); } } else { // Note that only a single item can be previewed. PreviewAddon addon = response.TargetAddon as PreviewAddon; if (!pnlPreview.Controls.Contains(addon.AddonPanel)) { pnlPreview.Controls.Clear(); addon.AddonPanel.Dock = DockStyle.Fill; addon.AddonPanel.Location = new System.Drawing.Point(10, 10); addon.AddonPanel.TabIndex = 0; pnlPreview.Controls.Add(addon.AddonPanel); } previewCtl = GetPreviewControl(); if (previewCtl != null) { previewCtl.NavigationAction += new BaseAddonCtl.NavigationActionEventHandler(OnNavigationAction); previewCtl.BeginPreview(args.Paths[0], args.AdditionalData); } } } else { PropBaseCtl propCtl = GetPropertiesControl(); if (propCtl != null) { propCtl.NavigationAction -= new BaseAddonCtl.NavigationActionEventHandler(OnNavigationAction); } if (failed) { Logger.LogTrace("View Properties Action has failed."); pnlProperties.Controls.Clear(); pnlProperties.Controls.Add(lblNoProperties); } else { PropertyAddon addon = response.TargetAddon as PropertyAddon; if (!pnlProperties.Controls.Contains(addon.AddonPanel)) { pnlProperties.Controls.Clear(); addon.AddonPanel.Dock = DockStyle.Fill; pnlProperties.Controls.Add(addon.AddonPanel); } propCtl = GetPropertiesControl(); if (propCtl != null) { propCtl.NavigationAction += new BaseAddonCtl.NavigationActionEventHandler(OnNavigationAction); propCtl.BeginEdit(args.Paths, args.AdditionalData); } } } } } catch (Exception ex) { ErrorDispatcher.DispatchError(ex, false); } finally { pnlPreview.ResumeLayoutEx(); pnlProperties.ResumeLayoutEx(); this.ResumeLayoutEx(); Application.UseWaitCursor = false; Logger.LogTrace("MainForm handled OnNavigationAction."); } }
public async Task <ActionResponse> Register(UserRegisterBindingModel model) { Query query = new Query(); string PhoneNumber = Regex.Replace(model.PhoneNumber, @" ", ""); ActionResponse response = new ActionResponse(); ApplicationUser user = new ApplicationUser(); user = null; try { var data = JsonConvert.SerializeObject(model); query.SaveTxtLog(data); if (!ModelState.IsValid) { foreach (ModelState modelState in ModelState.Values) { foreach (ModelError error in modelState.Errors) { query.SaveTxtLog(string.Format("Registeration Error {0}: {1}", DebugCodes.ModelError, error.ErrorMessage)); response.errors.Add(error.ErrorMessage); } } response.success = false; response.code = String.Format("{0}", (int)HttpStatusCode.BadRequest); response.message = " Invalid User Information"; return(response); } var account_code = "QPAN"; if (model.IDCardNumber.ToLower() != "na") { if (model.IDCardNumber.Length != 11) { response.success = false; response.code = String.Format("{0}", (int)HttpStatusCode.BadRequest); response.message = " Invalid QID number"; return(response); } account_code = $"1{model.IDCardNumber.Substring(3, 3)}{model.IDCardNumber.Substring(model.IDCardNumber.Length - 8)}"; } user = new ApplicationUser() { UserName = model.Email, Email = model.Email, IDCardNumber = model.IDCardNumber, CountryID = 0, FirstName = model.FirstName, LastName = model.LastName, PhoneNumber = PhoneNumber, UserStatusID = 2, UserCode = account_code, JoiningDate = DateTime.Now, IsPinVerified = false, IsIDVerified = false, PinVerifiedDate = DateTime.Now, EmailVerifiedDate = DateTime.Now, IDExpiredDate = DateTime.Now, IDVerifiedDate = DateTime.Now, PhoneVerifiedDate = DateTime.Now, UserType = model.UserType, QpanExpiry = DateTime.Now.AddYears(5), }; query.SaveTxtLog("Registration Create process started "); IdentityResult result = await UserManager.CreateAsync(user, model.Password); query.SaveTxtLog(string.Format(" {0}: User Created", DebugCodes.Success)); if (!result.Succeeded) { response.success = false; response.message = "Error Creating User "; response.code = String.Format("{0}", (int)HttpStatusCode.BadRequest); if (result.Errors != null) { foreach (string error in result.Errors) { query.SaveTxtLog(string.Format("Registration Error {0}: {1}", DebugCodes.IdentitySaveError, error)); response.errors.Add(error); response.message += error + Environment.NewLine; } } return(response); } else { var userid = db.AspNetUsers.Where(d => d.UserCode.StartsWith(user.UserCode)).Count() + 1; if (userid.ToString().Length < 16) { // user.UserCode = account_code.PadRight(account_code.Length + (16 - userid.ToString().Length), '0') + userid.ToString(); string usercode = db.AspNetUsers.Count().ToString(); query.SaveTxtLog("usercode:" + usercode); query.SaveTxtLog("usercode length:" + usercode.ToString().Length); query.SaveTxtLog("user ID:" + userid); user.UserCode = userid.ToString().PadLeft(16 - usercode.ToString().Length, '0') + usercode.ToString(); } else { user.UserCode = user.UserCode + userid.ToString(); } user.ProfileImagePath = "na.jpg"; IdentityResult result2 = await UserManager.UpdateAsync(user); query.SaveTxtLog(string.Format(" {0}: User Updated", DebugCodes.Success)); if (!result2.Succeeded) { var delete_user = await UserManager.DeleteAsync(user); response.success = false; response.message = "Error Creating User "; response.code = String.Format("{0}", (int)HttpStatusCode.BadRequest); if (result.Errors != null) { foreach (string error in result.Errors) { query.SaveTxtLog(string.Format("Registration Update Error {0}: {1}", DebugCodes.IdentitySaveError, error)); response.errors.Add(error); response.message += error + Environment.NewLine; } } return(response); } else { var role = await UserManager.AddToRoleAsync(user.Id, user.UserType == 1? "Wallet User" : "Merchant"); if (!role.Succeeded) { var delete_user = await UserManager.DeleteAsync(user); response.success = false; response.message = "Error Creating User "; response.code = String.Format("{0}", (int)HttpStatusCode.BadRequest); if (result.Errors != null) { foreach (string error in result.Errors) { query.SaveTxtLog(string.Format("Registration Role Error {0}: {1}", DebugCodes.IdentitySaveError, error)); response.errors.Add(error); // response.Message += error + Environment.NewLine; } } return(response); } else { string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); var callbackUrl = Url.Link("Default", new { controller = "Home", action = "ConfirmNewEmail", userId = user.Id, code = code }); query.SaveTxtLog("email code" + code); var IsEmailSend = await query.SendEmailAsync(new SendMailModel { //Body = EmailModels.Templates.NewUserTemplate(model.UserName, model.FirstName + " " + model.LastName, model.Password, "<a href=\"" + callbackUrl + "\">here</a>", code), Body = NewUserTemplate(model.FirstName + " " + model.LastName, model.Email, model.Password, callbackUrl, code), Subject = "Qatar Pay Confirm your account", ToEmailAddress = user.Email }); if (IsEmailSend) { response.message = "User Created Succesfully "; } else { response.message = "User Created Succesfully, Unable to Send Email"; } } } } response.success = true; response.code = String.Format("{0}", (int)HttpStatusCode.OK); query.SaveTxtLog(string.Format(" {0}: User Created succesfully.", DebugCodes.Success)); return(response); } catch (Exception e) { if (user != null) { IdentityResult delete_user = await UserManager.DeleteAsync(user); } query.SaveTxtLog(string.Format(" {0} - {1}: Error Registering User {2}", "Account Controller (Registeration)", DebugCodes.Exception, e.ToString())); response.success = false; response.message = "Error Creating User "; response.code = String.Format("{0}", (int)HttpStatusCode.ExpectationFailed); return(response); } }
public ActionResponseBuilder() { _actionResponse = new ActionResponse <T>(); }
public ActionResponse Execute() { if (_output.Process.Entities.Sum(e => e.Inserts + e.Updates + e.Deletes) == 0) { return(new ActionResponse(200, "nothing to flatten")); } var model = new AdoSqlModel(_output, _cf); if (_output.Process.Mode == "init") { return(new AdoFlattenFirstRunAction(_output, _cf, model).Execute()); } ActionResponse updateResponse = null; ActionResponse insertResponse = null; using (var cn = _cf.GetConnection(Constants.ApplicationName)) { cn.Open(); using (var trans = cn.BeginTransaction()) { _output.Info("Begin Flat Insert/Update Transaction"); if (model.MasterEntity.Inserts > 0) { if (_cf.AdoProvider == AdoProvider.SqlCe) { insertResponse = new AdoFlattenInsertBySelectAction(_output, _cf, model, cn, trans).Execute(); insertResponse.Action = new Action { Type = "internal", Description = "Flatten Action", ErrorMode = "abort" }; if (insertResponse.Code != 200) { trans.Rollback(); return(insertResponse); } } else { insertResponse = new AdoFlattenInsertByViewAction(_output, _cf, model, cn, trans).Execute(); insertResponse.Action = new Action { Type = "internal", Description = "Flatten Action", ErrorMode = "abort" }; if (insertResponse.Code != 200) { trans.Rollback(); return(insertResponse); } } } switch (_cf.AdoProvider) { case AdoProvider.SqlCe: // this provider does NOT support views, and does NOT support UPDATE ... SET ... FROM ... syntax var masterAlias = Utility.GetExcelName(model.MasterEntity.Index); var builder = new StringBuilder(); builder.AppendLine($"SELECT {_output.SqlStarFields(_cf)}"); foreach (var from in _output.SqlStarFroms(_cf)) { builder.AppendLine(@from); } builder.AppendFormat("INNER JOIN {0} flat ON (flat.{1} = {2}.{3})", _cf.Enclose(_output.Process.Name + _output.Process.FlatSuffix), model.EnclosedKeyLongName, masterAlias, model.EnclosedKeyShortName); builder.AppendLine($" WHERE {masterAlias}.{model.Batch} > @Threshold; "); //todo: add common cn and trans updateResponse = new AdoFlattenTwoPartUpdateAction(_output, _cf, model, builder.ToString(), cn, trans).Execute(); break; case AdoProvider.SqLite: // this provider supports views, but does NOT support UPDATE ... SET ... FROM ... syntax var sql = $@" SELECT s.{string.Join(",s.", model.Aliases)} FROM {model.Master} m INNER JOIN {model.Flat} f ON (f.{model.EnclosedKeyLongName} = m.{model.EnclosedKeyShortName}) INNER JOIN {model.Star} s ON (s.{model.EnclosedKeyLongName} = m.{model.EnclosedKeyShortName}) WHERE m.{model.Batch} > @Threshold;"; //todo: add common cn and trans updateResponse = new AdoFlattenTwoPartUpdateAction(_output, _cf, model, sql, cn, trans).Execute(); break; default: // these providers support views and UPDATE ... SET ... FROM ... syntax (server based) updateResponse = new AdoFlattenUpdateByViewAction(_output, model, cn, trans).Execute(); break; } if (updateResponse.Code == 200) { trans.Commit(); _output.Info("Committed Flat Insert/Update Transaction"); } else { updateResponse.Action = new Action { Type = "internal", Description = "Flatten Action", ErrorMode = "abort" }; trans.Rollback(); _output.Warn("Rolled Back Flat Insert/Update Transaction"); } return(updateResponse); } } }
public ActionResponseBuilder(T data) { _actionResponse = new ActionResponse <T>(data); }
public ActionResponse <OrderRequest> Save_Orders(OrderRequest model) { ActionResponse <OrderRequest> response = new ActionResponse <OrderRequest>() { Response = model, ResponseType = ResponseType.Ok }; using (MspDbContext _db = new MspDbContext()) { using (DbContextTransaction transaction = _db.Database.BeginTransaction()) { try { if (_db.OrderOwner.Any(x => x.SiparisNo == model.OrderOwner.SiparisNo && x.RecId == 0 && x.Deleted == false)) { response.Message = "Aynı Sipariş No'dan vardır."; response.ResponseType = ResponseType.Error; return(response); } int OrderOwnerId = 0; if (response.Response.OrderOwner.RecId == 0) { OrderOwner orderOwner = base.Map <OrderOwnerDTO, OrderOwner>(model.OrderOwner); _db.OrderOwner.Add(orderOwner); _db.SaveChanges(); OrderOwnerId = orderOwner.RecId; } else { var entity = _db.OrderOwner.FirstOrDefault(x => x.RecId == response.Response.OrderOwner.RecId); if (entity != null) { _db.Entry(entity).CurrentValues.SetValues(model.OrderOwner); _db.Entry(entity).State = System.Data.Entity.EntityState.Modified; } } foreach (var item in model.OrderTrans) { if (item.RecId == 0) { item.OwnerId = OrderOwnerId; _db.OrderTrans.Add(base.Map <OrderTransDTO, OrderTrans>(item)); //var product = _db.products.FirstOrDefault(x => x.PID == item.ProductId); //if (product != null) //{ // Products updatePro = new Products(); // updatePro = product; // updatePro.PTotal = updatePro.PTotal - item.ProductQuantity; // _db.Entry(product).CurrentValues.SetValues(updatePro); // _db.Entry(product).State = System.Data.Entity.EntityState.Modified; //} } else { var entity = _db.OrderTrans.FirstOrDefault(x => x.RecId == item.RecId); if (entity != null) { _db.Entry(entity).CurrentValues.SetValues(item); _db.Entry(entity).State = System.Data.Entity.EntityState.Modified; } } } _db.SaveChanges(); transaction.Commit(); } catch (Exception e) { transaction.Rollback(); response.Message = e.ToString(); response.ResponseType = ResponseType.Error; } } } return(response); }
public async Task <IActionResult> ShareDocument(int Id, string emails) { ActionResponse response = new ActionResponse { }; FileContentResult file = (FileContentResult) await GenerateDocument(Id, ""); var LabTest = tests.GetById(Id); string testing_date = Utils.Utils.toShortdate(LabTest.LabTest.TestingDate); string filename = string.Format("Covid19-{0}-{1}.pdf", LabTest.BioData.EpidNo, testing_date); Attachment data = new Attachment(new MemoryStream(file.FileContents), filename, MediaTypeNames.Application.Octet); // Gmail Address from where you send the mail var fromAddress = "*****@*****.**"; // any address where the email will be sending //var toAddress = "*****@*****.**"; //Password of your gmail address const string fromPassword = "******"; MailMessage message = new MailMessage(); message.IsBodyHtml = true; message.From = new MailAddress(fromAddress); foreach (var e in emails.Split(";")) { message.To.Add(new MailAddress(e)); } //message.To.Add(new MailAddress(toAddress)); //message.To.Add(new MailAddress("*****@*****.**")); message.Subject = string.Format("Covid19 Test Result, {0}", testing_date); string body = "Greetings, <br />"; body += string.Format("Covid19 Test Result for candicate EPID-No: {0}, Fullname: {1} <br />", LabTest.BioData.EpidNo, LabTest.BioData.Fullname); body += "Regards <br />"; body += "UN Migration/IOM/MHAC"; message.Body = body;//@"Using this new feature, you can send an email message from an application very easily."; // smtp settings message.Attachments.Add(data); var smtp = new System.Net.Mail.SmtpClient(); { smtp.Host = "smtp.gmail.com"; smtp.Port = 587; smtp.EnableSsl = true; smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; smtp.Credentials = new NetworkCredential(fromAddress, fromPassword); smtp.Timeout = 0; try { smtp.Send(message); LabTest.LabTest.SentEmailBy = User.Identity.Name; LabTest.LabTest.SentEmailTime = DateTime.Now; tests.Update(LabTest); response.IsSuccessful = true; response.Message = "n/a"; //response.JSONData = JsonConvert.SerializeObject(Indicators); } catch (Exception ex) { //Console.WriteLine("Exception caught in CreateTestMessage2(): {0}", // ex.ToString()); response.IsSuccessful = false; response.Message = ex.Message; //response.JSONData = JsonConvert.SerializeObject(Indicators); } } return(Json(response, new JsonSerializerSettings())); }
public ActionResult Create(AgentModel model, List <AgentBankModel> AgentBankModel, int[] ChkSettingId, FormCollection fc) { TravelSession obj = SessionStore.GetTravelSession(); model.BranchOfficeId = distributorManagementProvider.GetDistributorByDistributorId(obj.LoginTypeId).BranchOfficeId; model.DistributorId = obj.LoginTypeId; model.CreatedbyUser = obj.AppUserId; model.CreatedBy = LogedUserId; model.CreatedDate = CurrentDate; model.AgentStatusid = 1; model.EmailId = model.EmailId.Trim(';'); if (!_rep.CheckDuplicateEmail(model.Email)) { TempData["ErrorMessage"] = "Registration failed! Email already exists, please re-enter and try again"; AgentModel viewmodel = new AgentModel { ProductBaseRoleList = _rep.GetProductList(), }; ViewData["Countrylist"] = new SelectList(_rep.GetCountry(), "CountryId", "CountryName", 0); ViewData["Status"] = new SelectList(_rep.GetStatus(), "id", "Name", 1); ViewData["AirlineGroup"] = new SelectList(_rep.GetAirlineGroup(), "AirlineGroupId", "AirlineGroupName"); ViewData["RoleAssign"] = new SelectList("", "RoleName", "RoleName", ""); ViewData["AgentTypes"] = new SelectList(_rep.GetAgentType(), "AgentTypeId", "AgentTypeName"); ViewData["AgentZone"] = new SelectList(_rep.GetZoneList(), "ZoneId", "ZoneName"); ViewData["AgentDistrict"] = new SelectList(_rep.GetDistrictListbyZoneId(1), "DistrictId", "DistrictName"); ViewData["Banks"] = new SelectList(_rep.GetbankInformation(), "BankId", "BankName"); ViewData["BankBranches"] = new SelectList(_rep.GetbankBranchInformation(), "BankBranchId", "BranchName"); ViewData["BankAccountTypes"] = new SelectList(_rep.GetbankAccountType(), "BankAccountTypeId", "AccountTypeName"); ViewData["TimeZones"] = new SelectList(_rep.GetTimeZoneList(), "RecordID", "StandardName", 66); return(View("Create", viewmodel)); } else { if (!string.IsNullOrEmpty(model.MobileNo) && !_rep.CheckDuplicateMobileNumber(model.MobileNo)) { TempData["ErrorMessage"] = "Registration failed! Mobile Number already exists, please re-enter and try again"; AgentModel viewmodel = new AgentModel { ProductBaseRoleList = _rep.GetProductList(), }; ViewData["Countrylist"] = new SelectList(_rep.GetCountry(), "CountryId", "CountryName", 0); ViewData["Status"] = new SelectList(_rep.GetStatus(), "id", "Name", 1); ViewData["AirlineGroup"] = new SelectList(_rep.GetAirlineGroup(), "AirlineGroupId", "AirlineGroupName"); ViewData["RoleAssign"] = new SelectList("", "RoleName", "RoleName", ""); ViewData["AgentTypes"] = new SelectList(_rep.GetAgentType(), "AgentTypeId", "AgentTypeName"); ViewData["AgentZone"] = new SelectList(_rep.GetZoneList(), "ZoneId", "ZoneName"); ViewData["AgentDistrict"] = new SelectList(_rep.GetDistrictListbyZoneId(1), "DistrictId", "DistrictName"); ViewData["Banks"] = new SelectList(_rep.GetbankInformation(), "BankId", "BankName"); ViewData["BankBranches"] = new SelectList(_rep.GetbankBranchInformation(), "BankBranchId", "BranchName"); ViewData["BankAccountTypes"] = new SelectList(_rep.GetbankAccountType(), "BankAccountTypeId", "AccountTypeName"); ViewData["TimeZones"] = new SelectList(_rep.GetTimeZoneList(), "RecordID", "StandardName", 66); return(View("Create", viewmodel)); } else { int[] ChkProductId = new int[1] { 1 }; _res = _rep.Create(model, AgentBankModel, ChkProductId, fc); TempData["InfoMessage"] = _res.ActionMessage; if (_res.ErrNumber == 0) { return(RedirectToAction("Index")); } else { AgentModel viewmodel = new AgentModel { ProductBaseRoleList = _rep.GetProductList(), }; TempData["ErrorMessage"] = "Registration failed! Either Enter Username or Your passwords must match, please re-enter and try again"; ViewData["Countrylist"] = new SelectList(_rep.GetCountry(), "CountryId", "CountryName", 0); ViewData["Status"] = new SelectList(_rep.GetStatus(), "id", "Name", 1); ViewData["AirlineGroup"] = new SelectList(_rep.GetAirlineGroup(), "AirlineGroupId", "AirlineGroupName"); ViewData["RoleAssign"] = new SelectList("", "RoleName", "RoleName", ""); ViewData["AgentTypes"] = new SelectList(_rep.GetAgentType(), "AgentTypeId", "AgentTypeName"); ViewData["AgentZone"] = new SelectList(_rep.GetZoneList(), "ZoneId", "ZoneName"); ViewData["AgentDistrict"] = new SelectList(_rep.GetDistrictListbyZoneId(1), "DistrictId", "DistrictName"); ViewData["Banks"] = new SelectList(_rep.GetbankInformation(), "BankId", "BankName"); ViewData["BankBranches"] = new SelectList(_rep.GetbankBranchInformation(), "BankBranchId", "BranchName"); ViewData["BankAccountTypes"] = new SelectList(_rep.GetbankAccountType(), "BankAccountTypeId", "AccountTypeName"); ViewData["TimeZones"] = new SelectList(_rep.GetTimeZoneList(), "RecordID", "StandardName", 66); return(View("Create", viewmodel)); } } } }
public IActionResult Update() { ActionResponse actionResponse = new ActionResponse(); return(actionResponse.ToIActionResult()); }
public ActionResponse CancelRequest(int projectId, int userId) { using (var unitWork = new UnitOfWork(context)) { IMessageHelper mHelper; ActionResponse response = new ActionResponse(); var project = unitWork.ProjectRepository.GetByID(projectId); if (project == null) { mHelper = new MessageHelper(); response.Success = false; response.Message = mHelper.GetNotFound("Project"); return(response); } var userOrganizationsList = unitWork.UserRepository.GetProjection(u => u.Id == userId, u => u.OrganizationId); var userOrganizationId = (from orgId in userOrganizationsList select orgId).FirstOrDefault(); int projectOrganizationId = 0; EFProjectDeletionRequests deletionRequest = null; var deletionRequestArr = unitWork.ProjectDeletionRepository.GetWithInclude(d => d.ProjectId == projectId, new string[] { "RequestedBy" }); foreach (var delRequest in deletionRequestArr) { projectOrganizationId = delRequest.RequestedBy.OrganizationId; deletionRequest = delRequest; } bool canEditProject = false; if (projectOrganizationId == userOrganizationId) { canEditProject = true; } else { var funderProjectsIds = unitWork.ProjectFundersRepository.GetProjection(f => f.FunderId == userOrganizationId, f => f.ProjectId).ToList(); var implementerProjectIds = unitWork.ProjectImplementersRepository.GetProjection(i => i.ImplementerId == userOrganizationId, i => i.ProjectId).ToList(); var membershipProjectIds = unitWork.ProjectMembershipRepository.GetProjection(m => (m.UserId == userId && m.IsApproved == true), m => m.ProjectId); var combinedProjectIds = funderProjectsIds.Union(implementerProjectIds); combinedProjectIds = combinedProjectIds.Union(membershipProjectIds); if (!combinedProjectIds.Contains(projectId)) { mHelper = new MessageHelper(); response.Success = false; response.Message = mHelper.GetInvalidProjectEdit(); return(response); } canEditProject = true; } if (canEditProject) { unitWork.ProjectDeletionRepository.Delete(deletionRequest); unitWork.Save(); var projectFunderIds = unitWork.ProjectFundersRepository.GetProjection(f => f.ProjectId == project.Id, f => f.FunderId); var projectImplementerIds = unitWork.ProjectImplementersRepository.GetProjection(i => i.ProjectId == project.Id, i => i.ImplementerId); var orgIds = projectFunderIds.Union(projectImplementerIds).ToList(); if (!orgIds.Contains(userOrganizationId)) { orgIds.Add(userOrganizationId); } var userEmails = unitWork.UserRepository.GetProjection(u => u.UserType == UserTypes.Standard && orgIds.Contains(u.OrganizationId), u => u.Email); var adminEmails = unitWork.UserRepository.GetProjection(u => u.UserType == UserTypes.Manager, u => u.Email); var allEmails = userEmails.Union(adminEmails); List <EmailAddress> usersEmailList = new List <EmailAddress>(); foreach (var email in allEmails) { usersEmailList.Add(new EmailAddress() { Email = email }); } if (usersEmailList.Count > 0) { ISMTPSettingsService smtpService = new SMTPSettingsService(context); var smtpSettings = smtpService.GetPrivate(); SMTPSettingsModel smtpSettingsModel = new SMTPSettingsModel(); if (smtpSettings != null) { smtpSettingsModel.Host = smtpSettings.Host; smtpSettingsModel.Port = smtpSettings.Port; smtpSettingsModel.Username = smtpSettings.Username; smtpSettingsModel.Password = smtpSettings.Password; smtpSettingsModel.AdminEmail = smtpSettings.AdminEmail; smtpSettingsModel.SenderName = smtpSettings.SenderName; } string message = "", subject = "", footerMessage = ""; string projectTitle = "<h5>Project title: " + project.Title + "</h5>"; var emailMessage = unitWork.EmailMessagesRepository.GetOne(m => m.MessageType == EmailMessageType.ProjectDeletionCancelled); if (emailMessage != null) { subject = emailMessage.Subject; message = projectTitle + emailMessage.Message; footerMessage = emailMessage.FooterMessage; } IEmailHelper emailHelper = new EmailHelper(smtpSettingsModel.AdminEmail, smtpSettings.SenderName, smtpSettingsModel); emailHelper.SendEmailToUsers(usersEmailList, subject, "", message, footerMessage); } } return(response); } }
public PaymentController(PaymentContext context, ItemContext itemContext, StockContext stockContext, UserContext userContext, ActionResponse actionContext, LogContext logContext, UserLogContext userLogContext, BalanceContext balanceContext) { _context = context; _itemContext = itemContext; _stockContext = stockContext; _userContext = userContext; _actionContext = actionContext; _logContext = logContext; _userLogContext = userLogContext; _balanceContext = balanceContext; }
public ActionResponse SendPendingDeletionRequestsToManagement() { ActionResponse response = new ActionResponse(); var unitWork = new UnitOfWork(context); var pendingDeletionRequests = unitWork.ProjectDeletionRepository.GetWithInclude(d => d.Status == ProjectDeletionStatus.Requested && d.RequestedOn <= DateTime.Now.AddDays(-7) && !d.IsNotifiedToManager, new string[] { "Project", "RequestedBy" }); var users = unitWork.UserRepository.GetWithInclude(u => u.UserType == UserTypes.Manager, new string[] { "Organization" }); var adminEmails = (from u in users select u.Email); List <EmailAddress> usersEmailList = new List <EmailAddress>(); foreach (var email in adminEmails) { usersEmailList.Add(new EmailAddress() { Email = email }); } if (usersEmailList.Count > 0) { ISMTPSettingsService smtpService = new SMTPSettingsService(context); var smtpSettings = smtpService.GetPrivate(); SMTPSettingsModel smtpSettingsModel = new SMTPSettingsModel(); if (smtpSettings != null) { smtpSettingsModel.Host = smtpSettings.Host; smtpSettingsModel.Port = smtpSettings.Port; smtpSettingsModel.Username = smtpSettings.Username; smtpSettingsModel.Password = smtpSettings.Password; smtpSettingsModel.AdminEmail = smtpSettings.AdminEmail; smtpSettingsModel.SenderName = smtpSettings.SenderName; } var projectIds = (from p in pendingDeletionRequests select p.ProjectId).ToList <int>(); foreach (var request in pendingDeletionRequests) { var receiversEmails = (from e in usersEmailList where e.Email != request.RequestedBy.Email select e).ToList(); string message = "", subject = "", footerMessage = ""; string projectTitle = "<h5>Project title: " + request.Project.Title + "</h5>"; string requestedBy = "<h5>Requested by: " + request.RequestedBy.Email + "</h5>"; var emailMessage = unitWork.EmailMessagesRepository.GetOne(m => m.MessageType == EmailMessageType.ProjectDeletionRequest); if (emailMessage != null) { subject = emailMessage.Subject; message = projectTitle + requestedBy + emailMessage.Message; footerMessage = emailMessage.FooterMessage; } IEmailHelper emailHelper = new EmailHelper(smtpSettingsModel.AdminEmail, smtpSettings.SenderName, smtpSettingsModel); emailHelper.SendEmailToUsers(receiversEmails, subject, "", message, footerMessage); request.IsNotifiedToManager = true; unitWork.ProjectDeletionRepository.Update(request); } if (pendingDeletionRequests.Any()) { unitWork.Save(); } } return(response); }
public static bool SubmitOrder(AvventoServiceClient avventoServiceClient, string instrumentCode, string clientAccountReference, string clientCodeOrAccountNumber, string memberCode, string dealerCode, string buyOrSell, int icebergqty, int qty, double price, string userName, int bidType, int cancelFlag, string orderReferenceNumber, DateTime expiryDate, out ActionResponse actionresponse) { actionresponse = null; string query = System.IO.File.ReadAllText(@"templates\1.SubmitOrderClientCode.xml"); query = query.Replace("@InstrumentCode", instrumentCode); query = query.Replace("@ClientAccountReference", clientAccountReference); query = query.Replace("@ClientCodeOrAccountNumber", clientCodeOrAccountNumber); query = query.Replace("@DealerCode", dealerCode); query = query.Replace("@MemberCode", memberCode); query = query.Replace("@BuyOrSell", buyOrSell); query = query.Replace("@Quantity", qty.ToString()); query = query.Replace("@IceBergQuantity", icebergqty.ToString()); query = query.Replace("@Price", price.ToString()); query = query.Replace("@BidType", bidType.ToString()); query = query.Replace("@ExpiryDate", expiryDate.ToString("yyyy-MM-dd")); query = query.Replace("@CancelFlag", cancelFlag.ToString()); query = query.Replace("@OrderReference", orderReferenceNumber); string xmlresult = avventoServiceClient.SubmitAction(query); actionresponse = XmlParser.FromXml <ActionResponse>(xmlresult); if (actionresponse.ResponseCode == "0") { return(true); } else { return(false); } }
public async Task <ActionResponse> AddAsync(EnvelopeModel model, int funderId) { using (var unitWork = new UnitOfWork(context)) { ActionResponse response = new ActionResponse(); try { var envelope = unitWork.EnvelopeRepository.GetOne(e => e.FunderId == funderId); int fyMonth = 1, fyDay = 1; var fySettings = unitWork.FinancialYearSettingsRepository.GetOne(fy => fy.Id != 0); if (fySettings != null) { fyMonth = fySettings.Month; fyDay = fySettings.Day; } int currentYear = DateTime.Now.Year, currentMonth = DateTime.Now.Month, currentDay = DateTime.Now.Day; bool isSimilarToCalendarYear = (fyMonth == 1 && fyDay == 1) ? true : false; if (!isSimilarToCalendarYear) { if (currentMonth < fyMonth) { --currentYear; } else if (currentMonth == fyMonth && currentDay < fyDay) { --currentYear; } } var financialYears = unitWork.FinancialYearRepository.GetManyQueryable(y => y.FinancialYear >= (currentYear - 1) && y.FinancialYear <= (currentYear + 1)); var envelopeTypes = unitWork.EnvelopeTypesRepository.GetManyQueryable(e => e.Id != 0); var strategy = context.Database.CreateExecutionStrategy(); await strategy.ExecuteAsync(async() => { using (var transaction = context.Database.BeginTransaction()) { if (envelope == null) { envelope = unitWork.EnvelopeRepository.Insert(new EFEnvelope() { FunderId = funderId, Currency = model.Currency, ExchangeRate = model.ExchangeRate, }); } else { envelope.Currency = model.Currency; envelope.ExchangeRate = model.ExchangeRate; unitWork.EnvelopeRepository.Update(envelope); } await unitWork.SaveAsync(); var yearlyBreakups = unitWork.EnvelopeYearlyBreakupRepository.GetWithInclude(e => e.EnvelopeId == envelope.Id, new string[] { "Year" }); List <EFEnvelopeYearlyBreakup> newYearlyBreakups = new List <EFEnvelopeYearlyBreakup>(); foreach (var breakup in model.EnvelopeBreakups) { var isBreakupExists = (from b in yearlyBreakups where b.Year.FinancialYear == breakup.Year && envelope.Id == b.EnvelopeId && b.EnvelopeTypeId == breakup.EnvelopeTypeId select b).FirstOrDefault(); if (isBreakupExists == null) { var financialYear = (from fy in financialYears where fy.FinancialYear == breakup.Year select fy).FirstOrDefault(); if (financialYear == null) { financialYear = unitWork.FinancialYearRepository.Insert(new EFFinancialYears() { FinancialYear = breakup.Year }); unitWork.Save(); } var envelopeType = (from t in envelopeTypes where t.Id == breakup.EnvelopeTypeId select t).FirstOrDefault(); if (envelopeType != null) { newYearlyBreakups.Add(new EFEnvelopeYearlyBreakup() { EnvelopeType = envelopeType, Year = financialYear, Amount = breakup.Amount, Envelope = envelope }); } } else { isBreakupExists.Amount = breakup.Amount; unitWork.EnvelopeYearlyBreakupRepository.Update(isBreakupExists); unitWork.Save(); } } if (newYearlyBreakups.Count > 0) { unitWork.EnvelopeYearlyBreakupRepository.InsertMultiple(newYearlyBreakups); await unitWork.SaveAsync(); } transaction.Commit(); } }); } catch (Exception ex) { response.Success = false; response.Message = ex.Message; } return(response); } }
public async Task DeployFacebookTemplate() { var dataStore = await TestManager.GetDataStore(true); dataStore.AddToDataStore("FacebookClientId", "422676881457852"); dataStore.AddToDataStore("FacebookClientSecret", "bf5fca097936ece936290031623b577b"); dataStore.AddToDataStore("SqlConnectionString", "Server=tcp:modb1.database.windows.net,1433;Initial Catalog=fb4;Persist Security Info=False;User ID=pbiadmin;Password=Corp123!;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"); dataStore.AddToDataStore("Schema", "fb"); dataStore.AddToDataStore("SqlServerIndex", "0"); dataStore.AddToDataStore("SqlScriptsFolder", "Database"); dataStore.AddToDataStore("SqlGroup", "SolutionTemplate"); dataStore.AddToDataStore("SqlSubGroup", "ETL"); dataStore.AddToDataStore("SqlEntryName", "PagesToFollow"); dataStore.AddToDataStore("SqlEntryValue", "dcextendeduniverse,MarvelCinematicUniverse"); dataStore.AddToDataStore("SqlConfigTable", "fb.configuration"); ActionResponse response = null; dataStore.AddToDataStore("DeploymentName", "FunctionDeploymentTest1"); dataStore.AddToDataStore("CognitiveServiceName", "TextCognitiveService"); dataStore.AddToDataStore("CognitiveServiceType", "TextAnalytics"); dataStore.AddToDataStore("CognitiveSkuName", "S1"); response = TestManager.ExecuteAction("Microsoft-DeployCognitiveService", dataStore); Assert.IsTrue(response.IsSuccess); response = TestManager.ExecuteAction("Microsoft-GetCognitiveKey", dataStore); Assert.IsTrue(response.IsSuccess); response = await TestManager.ExecuteActionAsync("Microsoft-WaitForCognitiveService", dataStore, "Microsoft-FacebookTemplate"); Assert.IsTrue(response.IsSuccess); response = await TestManager.ExecuteActionAsync("Microsoft-DeploySQLScripts", dataStore, "Microsoft-FacebookTemplate"); Assert.IsTrue(response.IsSuccess); response = await TestManager.ExecuteActionAsync("Microsoft-SetConfigValueInSql", dataStore, "Microsoft-FacebookTemplate"); Assert.IsTrue(response.IsSuccess); // Testing to see if the tear down works response = await TestManager.ExecuteActionAsync("Microsoft-DeploySQLScripts", dataStore, "Microsoft-FacebookTemplate"); Assert.IsTrue(response.IsSuccess); response = await TestManager.ExecuteActionAsync("Microsoft-SetConfigValueInSql", dataStore, "Microsoft-FacebookTemplate"); Assert.IsTrue(response.IsSuccess); dataStore.AddToDataStore("DeploymentName", "FunctionDeploymentTest1"); dataStore.AddToDataStore("FunctionName", "unittestfunction1154789"); dataStore.AddToDataStore("RepoUrl", "https://github.com/MohaaliMicrosoft/FacebookExtraction"); dataStore.AddToDataStore("sku", "Standard"); response = TestManager.ExecuteAction("Microsoft-DeployAzureFunction", dataStore); Assert.IsTrue(response.IsSuccess); dataStore.AddToDataStore("DeploymentName", "FunctionDeploymentTest2"); dataStore.AddToDataStore("StorageAccountName", "testmostorage12345678"); dataStore.AddToDataStore("StorageAccountType", "Standard_LRS"); dataStore.AddToDataStore("StorageAccountEncryptionEnabled", "true"); response = TestManager.ExecuteAction("Microsoft-CreateAzureStorageAccount", dataStore); Assert.IsTrue(response.IsSuccess); dataStore.AddToDataStore("DeploymentName", "FunctionDeploymentTest1"); response = TestManager.ExecuteAction("Microsoft-WaitForArmDeploymentStatus", dataStore); Assert.IsTrue(response.IsSuccess); dataStore.AddToDataStore("DeploymentName", "FunctionDeploymentTest2"); response = TestManager.ExecuteAction("Microsoft-WaitForArmDeploymentStatus", dataStore); Assert.IsTrue(response.IsSuccess); response = TestManager.ExecuteAction("Microsoft-GetStorageAccountKey", dataStore); Assert.IsTrue(response.IsSuccess); dataStore.AddToDataStore("ConnectorName", "azurequeues"); JObject connector = new JObject(); connector.Add("sharedkey", dataStore.GetValue("StorageAccountKey")); connector.Add("storageaccount", dataStore.GetValue("StorageAccountName")); dataStore.AddToDataStore("ConnectorPayload", connector); response = await TestManager.ExecuteActionAsync("Microsoft-UpdateBlobStorageConnector", dataStore, "Microsoft-FacebookTemplate"); Assert.IsTrue(response.IsSuccess); dataStore.AddToDataStore("DeploymentName", "FunctionDeploymentTest"); JObject val = new JObject(); val.Add("queue", dataStore.GetValue("StorageAccountConnectionString")); dataStore.AddToDataStore("AppSettingKeys", val); response = TestManager.ExecuteAction("Microsoft-DeployAzureFunctionAppSettings", dataStore); Assert.IsTrue(response.IsSuccess); JObject val2 = new JObject(); val2.Add("SqlConnectionString", dataStore.GetValue("SqlConnectionString")); val2.Add("CognitiveKey", dataStore.GetValue("CognitiveServiceKey")); val2.Add("Schema", dataStore.GetValue("Schema")); val2.Add("FacebookClientId", dataStore.GetValue("FacebookClientId")); val2.Add("FacebookClientSecret", dataStore.GetValue("FacebookClientSecret")); dataStore.AddToDataStore("AppSettingKeys", val2); response = TestManager.ExecuteAction("Microsoft-DeployAzureFunctionConnectionStrings", dataStore); Assert.IsTrue(response.IsSuccess); dataStore.AddToDataStore("AzureArmFile", "Service/Arm/logicapps.json"); JObject logicapps = new JObject(); logicapps.Add("functionname", dataStore.GetValue("FunctionName")); logicapps.Add("storageName", dataStore.GetValue("StorageAccountName")); logicapps.Add("subscription", dataStore.GetJson("SelectedSubscription", "SubscriptionId")); logicapps.Add("resourceGroup", dataStore.GetValue("SelectedResourceGroup")); logicapps.Add("days", "3000"); dataStore.AddToDataStore("AzureArmParameters", logicapps); response = await TestManager.ExecuteActionAsync("Microsoft-DeployAzureArmTemplate", dataStore, "Microsoft-FacebookTemplate"); Assert.IsTrue(response.IsSuccess); }
public RequestOption(ActionResponse actionResponse, string actionResponseText) { ActionResponse = actionResponse; ActionResponseText = actionResponseText; }
/// <summary> /// Create a new custody for a puntual product, reserving any value sent it /// </summary> /// <param name="idProduct"></param> /// <param name="ani"></param> /// <param name="value"></param> /// <returns></returns> public ActionResponse CustodyRequestFromPlatformAction(int idProduct, string ani, string value) { ActionResponse output = new ActionResponse(); try { // STEP 1: VALIDATE actions // Call for platform's sp to get id_user from ani decimal id_cliente = clienteData.FindIdUserFromAni(ani); if (id_cliente == 0) { return(functions.Response((int)CodeStatusEnum.NO_CONTENT, "No se ha encontrado el usuario relacionado al ani proporcionado", null)); } // Validate idProduct exists Product oProduct = productData.GetProductById(idProduct); if (oProduct == null) { return(functions.Response((int)CodeStatusEnum.NO_CONTENT, "El producto no existe en el sistema", null)); } // STEP 2: CREATE actions // Create UserIdentify /*int idUserIdentify = userIdentData.CreateUserIdentify(id_cliente, (int)ChannelEnum.ANI, ani); * if(idUserIdentify == 0) * { * return functions.Response((int)CodeStatusEnum.CONFLICT, "No se pudo crear la identificación del usuario", null); * }*/ // Calculate expiration date int minutes = Int32.Parse(functions.ConfigItem("MINUTES_CUSTODY_EXPIRATION")); DateTime today = DateTime.Now; string code = Guid.NewGuid().ToString(); // Generate alias for code (user could access without link) int max = Int32.Parse(functions.ConfigItem("MAX_ALIAS_CUSTODY")); string alias = functions.GetUniqueKey(max); // Create Custody element /* * attrs.Add("idProduct", idProduct); * attrs.Add("id_cliente", id_cliente); * attrs.Add("value", value); * attrs.Add("code", code); * attrs.Add("alias", alias); * attrs.Add("active", active); * attrs.Add("creationDate", creationDate); * attrs.Add("expirationDate", expirationDate); */ int idCustody = custodyData.CreateCustody(idProduct, id_cliente, value, code, alias, true, today, today.AddMinutes(minutes)); if (idCustody == 0) { return(functions.Response((int)CodeStatusEnum.CONFLICT, "No fue posible crear la solicitud de custodia", null)); } // URL where user will access to register or whatever needs to do /*string link = (oProduct.urlOperatorRegister == null) ? "" : oProduct.urlOperatorRegister; * * string linkCode = ""; * if(link.Contains("?")) * { * linkCode = link + "&code=" + alias; * } * else * { * linkCode = link + "?code=" + alias; * }*/ // OK CreateCustodyResponse res = new CreateCustodyResponse(); res.idClient = (int)id_cliente; res.idCustody = idCustody; res.alias = alias; res.code = code; res.url = oProduct.urlOperatorRegister; return(functions.Response((int)CodeStatusEnum.OK, "OK", res)); } catch (Exception e) { logger.Fatal(e.Message); return(functions.Response((int)CodeStatusEnum.INTERNAL_ERROR, e.Message, null)); } }
public ApplicationSettingViewModel Get(int?id, out ActionResponse _ores) { if (id != null) { if (IsExists(id.Value) == true) { var model = (from aa in _ent.AppSettings.Where(ii => ii.ProductId == id) select new ApplicationSettingViewModel { AppSettingId = aa.AppSettingId, ProductId = aa.ProductId, HFProductId = aa.ProductId, EnablePasswordRetrieval = aa.EnablePasswordRetrieval, EnablePasswordReset = aa.EnablePasswordReset, RequiresQuestionAndAnswer = aa.RequiresQuestionAndAnswer, RequiresUniqueEmail = aa.RequiresUniqueEmail, MaxInvalidPasswordAttempts = aa.MaxInvalidPasswordAttempts, MinRequiredPasswordLength = aa.MinRequiredPasswordLength, MinRequiredNonalphanumericCharacters = aa.MinRequiredNonalphanumericCharacters, PasswordAttemptWindow = aa.PasswordAttemptWindow, AppDateFormat = aa.AppDateFormat, SMTPServer = aa.SMTPServer, SMTPPort = aa.SMTPPort, SMTPUsername = aa.SMTPUsername, SMTPPassword = aa.SMTPPassword, EnableExpirePasswordWhenUserNotLoginFromDays = aa.EnableExpirePasswordWhenUserNotLoginFromDays, EnableAutoExpirePassword = aa.EnableAutoExpirePassword, AutoPasswordExpiryInDays = aa.AutoPasswordExpiryInDays, ShowPassowrdExpireNotificationBeforeDays = aa.ShowPassowrdExpireNotificationBeforeDays, Paggination = aa.Paggination, }).SingleOrDefault(); _ores = _res; if (model != null) { model.Flag = true; model.ddlProductList = new SelectList(GetProductList(), "ProductId", "ProductName", 0); return(model); } else { _model.Flag = true; _model.ddlProductList = new SelectList(GetProductList(), "ProductId", "ProductName", 0); return(_model); } } else { _res.ActionMessage = String.Format(Resources.Message.InvalidOperation, "Application Setting"); _res.ErrNumber = 1005; _res.ErrSource = "DataBase"; _res.ErrType = "App"; _res.ResponseStatus = true; _ores = _res; return(_model); } } else { _res.ActionMessage = String.Format(Resources.Message.InvalidOperation, "Application Setting"); _res.ErrNumber = 1005; _res.ErrSource = "DataBase"; _res.ErrType = "App"; _res.ResponseStatus = true; _ores = _res; return(_model); } //_ores = _res; //return null; }
public ActionResponse VerifyQID(VerifyPassportRequest post) { ActionResponse response = new ActionResponse(); try { if (!ModelState.IsValid) { foreach (ModelState modelState in ModelState.Values) { foreach (ModelError error in modelState.Errors) { query.SaveTxtLog(string.Format("Phone Verification Error {0}: {1}", DebugCodes.ModelError, error.ErrorMessage)); response.errors.Add(error.ErrorMessage); } } response.success = false; response.code = String.Format("{0}", (int)HttpStatusCode.BadRequest); response.message = "Invalid Model Detail"; return(response); } AspNetUser users = new AspNetUser(); users = db.AspNetUsers.Where((AspNetUser x) => x.UserSequence == post.UserID).FirstOrDefault(); if (users != null) { var account_code = "QPAN"; if (users.IDCardNumber.ToLower() != "na") { if (users.IDCardNumber.Length != 11) { response.success = false; response.code = String.Format("{0}", (int)HttpStatusCode.BadRequest); response.message = " Invalid QID number"; return(response); } //account_code = $"1{users.IDCardNumber.Substring(3, 3)}{users.IDCardNumber.Substring(users.IDCardNumber.Length - 8)}"; //query.SaveTxtLog("Account Code:" + account_code); //var userid = db.AspNetUsers.Where(d => d.UserCode.StartsWith(users.UserCode)).Count() + 1; //query.SaveTxtLog("Lenght Code:" + userid); //if (userid.ToString().Length < 16) //{ // string usercode = db.AspNetUsers.Count().ToString(); // users.UserCode = userid.ToString().PadLeft(16 - usercode.ToString().Length, '0') + usercode.ToString(); // query.SaveTxtLog("New Code < :" + users.UserCode); //} //else //{ // users.UserCode = users.UserCode + userid.ToString(); // query.SaveTxtLog("New Code :" + users.UserCode); //} account_code = "1" + users.IDCardNumber.Substring(3, 3) + users.IDCardNumber.Substring(users.IDCardNumber.Length - 8); int userid = (from d in this.db.AspNetUsers where d.UserCode.StartsWith(users.UserCode) select d).Count <AspNetUser>() + 1; if (userid.ToString().Length < 4) { users.UserCode = account_code.PadRight(account_code.Length + (4 - userid.ToString().Length), '0') + userid.ToString(); } else { users.UserCode += userid.ToString(); } users.IsIDVerified = true; users.IDVerifiedDate = DateTime.Now; db.SaveChanges(); query.SendFCM("Congratulations, your Account is verified.", "Qapay Pay Account Verification", users.UserSequence); response.success = true; response.message = "Status changed successfully"; response.code = String.Format("{0}", (int)HttpStatusCode.OK); return(response); } else { response.success = false; response.message = "Invalid QID"; response.code = String.Format("{0}", (int)HttpStatusCode.BadRequest); return(response); } } else { response.success = false; response.message = "User data not found"; return(response); } return(response); } catch (Exception ex) { response.success = false; response.code = HttpStatusCode.ExpectationFailed.ToString(); response.message = ex.ToString(); return(response); } }
void SetResponsesFromXML() { good_responses = new List<ActionResponse>(); bad_responses = new List<ActionResponse>(); TextAsset textAsset = (TextAsset) Resources.Load("XMLs/action_responses"); XmlReader reader = XmlReader.Create(new StringReader(textAsset.text)); bool positive = true; ActionResponse current_response = new ActionResponse(); string current_node = ""; while(reader.Read()) { if(reader.NodeType == XmlNodeType.Element) { if(reader.Name == "Negative") { positive = false; } if(reader.Name == "Response") { current_response = new ActionResponse(); } if(reader.Name == "EnglishText") { current_node = "EnglishText"; } else if(reader.Name == "ChineseText") { current_node = "ChineseText"; } } else if(reader.NodeType == XmlNodeType.Text) { if(current_node == "ChineseText") { string val = StringUtils.RemoveNewlineAndIndents(reader.Value); current_response.chinese_text = val; if(positive) { good_responses.Add(current_response); } else { bad_responses.Add(current_response); } } else if(current_node == "EnglishText") { string val = StringUtils.RemoveNewlineAndIndents(reader.Value); current_response.english_text = val; } } } }
public static Entity GetEntity(ActionResponse res, string resultName) { ActionResult rs = res.GetResult(resultName); Dictionary<string, object> dict = rs.GetDict(0); Entity o = new Entity(dict); return o; }