public override void SendNotification(EbWebForm _this, EbConnectionFactory ConnFactory, Service service, FG_Root globals, ref int resp) { if (!string.IsNullOrWhiteSpace(this.RefId)) { try { service.Gateway.Send <EmailAttachmenResponse>(new SMSInitialRequest { RefId = this.RefId, Params = new List <Param> { { new Param { Name = "id", Type = ((int)EbDbTypes.Int32).ToString(), Value = _this.TableRowId.ToString() } } }, SolnId = _this.SolutionObj.SolutionID, UserAuthId = _this.UserObj.AuthId, UserId = _this.UserObj.UserId }); } catch (Exception ex) { string temp = $"Exception when tried to send EbFnSms\n Message: ${ex.Message} \nRefId: ${this.RefId} \nStackTrace: ${ex.StackTrace}"; throw new FormException($"Unable to process notification.", (int)HttpStatusCode.InternalServerError, ex.Message, temp); } resp++; } }
private void UpdateRedisAndNotifyUser(User OldUser, string Wc, SaveRoleMqRequest request) { try { IEbConnectionFactory factory = new EbConnectionFactory(request.SolnId, Redis); User NewUser = User.GetUserObject(factory.DataDB, OldUser.UserId, Wc, null, null); OldUser.Permissions = NewUser.Permissions; OldUser.Roles = NewUser.Roles; OldUser.RoleIds = NewUser.RoleIds; OldUser.UserGroupIds = NewUser.UserGroupIds; this.Redis.Set <IUserAuth>(request.SolnId + ":" + OldUser.UserId + ":" + Wc, OldUser); this.ServiceStackClient.BearerToken = request.BToken; this.ServiceStackClient.RefreshToken = request.RToken; this.ServiceStackClient.RefreshTokenUri = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_GET_ACCESS_TOKEN_URL); this.ServiceStackClient.Post <NotifyByUserIDResponse>(new NotifyByUserIDRequest { Link = "/UserDashBoard", Title = $"Your roles was changed successfully", UsersID = OldUser.UserId, User_AuthId = OldUser.AuthId, BToken = request.BToken, RToken = request.RToken }); NotifyByUserAuthId(request.BToken, request.RToken, OldUser.AuthId, "User role changed successfully", "cmd.UpdateUserMenu"); } catch (Exception ex) { Console.WriteLine("user role changes-send notification" + ex.Message + ex.StackTrace); } }
public bool Post(SlackAuthRequest req) { EbConnectionFactory dbFactory = new EbConnectionFactory(req.SolnId, this.Redis); if (req.IsNew) { try { string sql = "UPDATE eb_users SET slackjson = @slackjson WHERE id = @id"; var id = dbFactory.DataDB.DoQuery <Int32>(sql, new DbParameter[] { dbFactory.DataDB.GetNewParameter("slackjson", EbDbTypes.Json, EbSerializers.Json_Serialize(req.SlackJson)), dbFactory.DataDB.GetNewParameter("id", EbDbTypes.Int32, req.UserId) }); } catch (Exception e) { Console.WriteLine("Exception: " + e.ToString()); return(false); } } else { throw new NotImplementedException(); } return(true); }
public void SaveSMSLogs(SMSStatusLogMqRequest request) { EbConnectionFactory connectionFactory = new EbConnectionFactory(request.SolnId, this.Redis); try { string sql = $@"INSERT INTO eb_sms_logs (send_to, send_from, message_body, status, result, refid, metadata, retryof, con_id, eb_created_by, eb_created_at) VALUES (@to, @from, @message_body, @status, @result, @refid, @metadata, @retryof, @con_id, @user_id, {connectionFactory.DataDB.EB_CURRENT_TIMESTAMP}) RETURNING id;"; DbParameter[] parameters = { connectionFactory.DataDB.GetNewParameter("to", EbDbTypes.String, request.SentStatus.To), connectionFactory.DataDB.GetNewParameter("from", EbDbTypes.String, request.SentStatus.From), connectionFactory.DataDB.GetNewParameter("message_body", EbDbTypes.String, string.IsNullOrEmpty(request.SentStatus.Body)?string.Empty:request.SentStatus.Body), connectionFactory.DataDB.GetNewParameter("status", EbDbTypes.String, string.IsNullOrEmpty(request.SentStatus.Status)?string.Empty:request.SentStatus.Status), connectionFactory.DataDB.GetNewParameter("result", EbDbTypes.String, string.IsNullOrEmpty(request.SentStatus.Result)?string.Empty:request.SentStatus.Result), connectionFactory.DataDB.GetNewParameter("refid", EbDbTypes.String, string.IsNullOrEmpty(request.RefId)?string.Empty:request.RefId), connectionFactory.DataDB.GetNewParameter("metadata", EbDbTypes.Json, request.MetaData), connectionFactory.DataDB.GetNewParameter("retryof", EbDbTypes.Int32, request.RetryOf), connectionFactory.DataDB.GetNewParameter("con_id", EbDbTypes.Int32, request.SentStatus.ConId), connectionFactory.DataDB.GetNewParameter("user_id", EbDbTypes.Int32, request.UserId) }; var iCount = connectionFactory.DataDB.DoQuery(sql, parameters); } catch (Exception ex) { throw new Exception("Exception in Sms log Save : " + ex.Message); } }
public object ExecuteFormResource(EbApi Api, Service Service) { try { int RecordId = 0; NTVDict _params = new NTVDict(); foreach (KeyValuePair <string, object> p in Api.GlobalParams) { EbDbTypes _type; if (p.Value is int) { _type = EbDbTypes.Int32; } else //check other types here if required { _type = EbDbTypes.String; } _params.Add(p.Key, new NTV() { Name = p.Key, Type = _type, Value = p.Value }); } if (!string.IsNullOrWhiteSpace(this.DataIdParam) && Api.GlobalParams.ContainsKey(this.DataIdParam)) { int.TryParse(Convert.ToString(Api.GlobalParams[this.DataIdParam]), out RecordId); } InsertOrUpdateFormDataRqst request = new InsertOrUpdateFormDataRqst { RefId = this.Reference, PushJson = this.PushJson, UserId = Api.UserObject.UserId, UserAuthId = Api.UserObject.AuthId, RecordId = RecordId, LocId = Convert.ToInt32(Api.GlobalParams["eb_loc_id"]), SolnId = Api.SolutionId, WhichConsole = "uc", FormGlobals = new FormGlobals { Params = _params }, //TransactionConnection = TransactionConnection }; EbConnectionFactory ebConnection = new EbConnectionFactory(Api.SolutionId, Api.Redis); InsertOrUpdateFormDataResp resp = EbFormHelper.InsertOrUpdateFormData(request, Api.DataDB, Service, Api.Redis, ebConnection); if (resp.Status == (int)HttpStatusCode.OK) { return(resp.RecordId); } else { throw new Exception(resp.Message); } } catch (Exception ex) { throw new ApiException("[ExecuteFormResource], " + ex.Message); } }
public int PersistIntegration(string Sol_Id, EbConnectionFactory infra, int UserId) { int nid = 0; string query = @"INSERT INTO eb_integrations (solution_id, type, preference, eb_integration_conf_id, created_at, created_by, eb_del) VALUES (@solution_id, @type, @preference, @conf_id, NOW(), @uid, 'F') RETURNING id;"; if (Id > 0) { query += @"UPDATE eb_integrations SET eb_del = 'T', modified_at = NOW(), modified_by = @uid WHERE id = @id;"; } DbParameter[] parameters = { infra.DataDB.GetNewParameter("solution_id", EbDbTypes.String, Sol_Id), infra.DataDB.GetNewParameter("type", EbDbTypes.String, this.Type.ToString()), infra.DataDB.GetNewParameter("preference", EbDbTypes.Int32, (int)Preference), infra.DataDB.GetNewParameter("conf_id", EbDbTypes.Int32, this.ConfigId), infra.DataDB.GetNewParameter("uid", EbDbTypes.Int32, UserId), infra.DataDB.GetNewParameter("id", EbDbTypes.Int32, this.Id) }; EbDataSet ds = infra.DataDB.DoQueries(query, parameters); nid = Convert.ToInt32(ds.Tables[0].Rows[0][0]); return(nid); }
//Process => Notifications property + Notifications from nextStage script of review ctrl public static int SendNotifications(EbWebForm _this, EbConnectionFactory ConnFactory, Service service) { if (_this.Notifications?.Count == 0) { return(0); } int resp = 0; try { FG_Root globals = GlobalsGenerator.GetCSharpFormGlobals_NEW(_this, _this.FormData, _this.FormDataBackup, ConnFactory.DataDB, null, false); foreach (EbFormNotification ebFn in _this.Notifications) { if (!string.IsNullOrEmpty(ebFn.SendOnlyIf?.Code)) { object soi = _this.ExecuteCSharpScriptNew(ebFn.SendOnlyIf.Code, globals); if (!(soi is bool && Convert.ToBoolean(soi))) { Console.WriteLine($"SendNotifications [SendOnlyIf is not TRUE]: {ebFn.GetType().Name}({ebFn.Name}) skipped."); continue; } } ebFn.SendNotification(_this, ConnFactory, service, globals, ref resp); } } catch (FormException ex) { Console.WriteLine($"Exception: {ex.Message}\nCode: {ex.ExceptionCode}\nMessageInternal: {ex.MessageInternal}\nStackTraceInteranl: {ex.StackTraceInternal}"); } catch (Exception ex) { Console.WriteLine($"Exception: {ex.Message}\nStackTrace: {ex.StackTrace}"); } return(resp); }
public object ExecuteEmailRetriever(EbApi Api, Service Service, EbStaticFileClient FileClient, bool isMq) { try { EbConnectionFactory EbConnectionFactory = new EbConnectionFactory(Api.SolutionId, Api.Redis); if (EbConnectionFactory.EmailRetrieveConnection[this.MailConnection] != null) { RetrieverResponse retrieverResponse = EbConnectionFactory.EmailRetrieveConnection[this.MailConnection].Retrieve(Service, this.DefaultSyncDate, FileClient, Api.SolutionId, isMq, SubmitAttachmentAsMultipleForm); EbWebForm _form = Api.Redis.Get <EbWebForm>(this.Reference); SchemaHelper.GetWebFormSchema(_form); if (!(_form is null)) { WebformData data = _form.GetEmptyModel(); foreach (RetrieverMessage _m in retrieverResponse?.RetrieverMessages) { InsertFormData(_form, data, _m, this.Reference, Api.SolutionId, Api.UserObject, Api.Redis, Service, EbConnectionFactory); } } else { throw new ApiException("[ExecuteEmailRetriever], form objects is not in redis."); } } else { throw new ApiException("[ExecuteEmailRetriever], mail connection doesn't exist."); } }
public EbMqResponse Post(UploadFileRequest request) { Log.Info("Inside Upload Img MQ Service"); try { EbConnectionFactory _ebConnectionFactory = new EbConnectionFactory(request.SolnId, this.Redis); string filestore_sid = _ebConnectionFactory.FilesDB.UploadFile( request.FileRefId.ToString(), request.Byte, request.FileCategory, request.InfraConID ); string sql = _ebConnectionFactory.DataDB.EB_MQ_UPLOADFILE; DbParameter[] parameters = { _ebConnectionFactory.DataDB.GetNewParameter("filestoresid", EbDbTypes.String, filestore_sid), _ebConnectionFactory.DataDB.GetNewParameter("refid", EbDbTypes.Int32, request.FileRefId), _ebConnectionFactory.DataDB.GetNewParameter("length", EbDbTypes.Int64, request.Byte.Length), _ebConnectionFactory.DataDB.GetNewParameter("filedb_con_id", EbDbTypes.Int32, _ebConnectionFactory.FilesDB.UsedConId), _ebConnectionFactory.DataDB.GetNewParameter("is_image", EbDbTypes.Boolean, false) }; var iCount = _ebConnectionFactory.DataDB.DoQuery(sql, parameters); if (iCount.Rows.Capacity > 0 && request.UserAuthId != string.Empty) { this.ServerEventClient.BearerToken = request.BToken; this.ServerEventClient.RefreshToken = request.RToken; this.ServerEventClient.RefreshTokenUri = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_GET_ACCESS_TOKEN_URL); this.ServerEventClient.Post <NotifyResponse>(new NotifyUserIdRequest { Msg = request.FileRefId, Selector = StaticFileConstants.UPLOADSUCCESS, ToUserAuthId = request.UserAuthId, }); } } catch (Exception e) { Log.Error("UploadFile:" + e.ToString()); MqResponse.IsError = true; MqResponse.ErrorString = e.ToString(); } return(MqResponse); }
public User UpdateRedisUserObject(User user_redis, string SolnId, string UserId, string WC, string UserAuth_Id) { IEbConnectionFactory factory = new EbConnectionFactory(SolnId, Redis); User user = User.GetUserObject(factory.DataDB, int.Parse(UserId), WC, null, null); user_redis.Permissions = user.Permissions; user_redis.Roles = user.Roles; user_redis.RoleIds = user.RoleIds; user_redis.UserGroupIds = user.UserGroupIds; this.Redis.Set <IUserAuth>(UserAuth_Id, user_redis); return(user_redis); }
public int PersistDeleteIntegration(string Sol_Id, EbConnectionFactory infra, int UserId) { string query = @"UPDATE eb_integrations SET eb_del = 'T', modified_at = NOW(), modified_by = @uid WHERE id = @id;"; DbParameter[] parameters = { infra.DataDB.GetNewParameter("uid", EbDbTypes.Int32, UserId), infra.DataDB.GetNewParameter("id", EbDbTypes.Int32, this.Id) }; int ds = infra.DataDB.DoNonQuery(query, parameters); return(ds); }
public override object Logout(IServiceBase service, Authenticate request) { try { CustomUserSession session = service.GetSession() as CustomUserSession; User User = (service as AuthenticateService).Redis.Get <User>(session.UserAuthId); EbConnectionFactory EbConnectionFactory = service.TryResolve <IEbConnectionFactory>() as EbConnectionFactory; User.Logout(EbConnectionFactory.DataDB); } catch (Exception ex) { Console.WriteLine("Exception in Logout : " + ex.Message); } return(base.Logout(service, request)); }
public IDatabase GetDatastore(EbConnectionFactory EbConFactory) { IDatabase db; if (EbConFactory.DataDB.ConId == this.DataStore) { db = EbConFactory.DataDB; } else if (EbConFactory.SupportingDataDB != null && EbConFactory.SupportingDataDB.TryGetValue(this.DataStore, out IDatabase supportDb)) { db = supportDb; } else { db = EbConFactory.DataDB; } return(db); }
public static EbAzureNFClient Create(string iSolutionId, IRedisClient redis) { EbConnectionFactory factory = new EbConnectionFactory(iSolutionId, redis); if (factory == null) { throw new Exception("No connection object for sid " + iSolutionId); } MobileAppConnection con = factory?.MobileAppConnection; if (con == null || con.IsNFConnectionsEmpty()) { throw new Exception("Azure NotificationHub connections are empty"); } Console.WriteLine("Azure connection string :" + con.AzureNFConnection); Console.WriteLine("Azure HubName :" + con.AzureNFHubName); return(new EbAzureNFClient(con.AzureNFConnection, con.AzureNFHubName)); }
public DownloadFileResponse Get(DownloadBotExtImgRequest request) { DownloadFileResponse dfs = new DownloadFileResponse(); MemoryStream ms = null; byte[] fb = new byte[0]; string sFilePath = string.Format("../StaticFiles/botExt/{0}", request.RefId); EbConnectionFactory ebConnectionFactory = new EbConnectionFactory(request.SolnId, this.Redis); try { if (!System.IO.File.Exists(sFilePath)) { string qry_refId = @"SELECT B.imagequality_id, B.filestore_sid, B.filedb_con_id FROM eb_files_ref A, eb_files_ref_variations B WHERE A.id=B.eb_files_ref_id AND A.id=:fileref ORDER BY B.imagequality_id;"; DbParameter[] parameters = { ebConnectionFactory.DataDB.GetNewParameter("fileref", EbDbTypes.Int32, Convert.ToInt32(request.RefId)), }; EbDataTable t = ebConnectionFactory.DataDB.DoQuery(qry_refId, parameters); if (t.Rows.Count == 0) { throw new Exception("filestore_sid not found - FileRefId:" + request.ImageInfo.FileRefId + " Quality:" + request.ImageInfo.ImageQuality); } Dictionary <int, ImageMeta> sidAll = new Dictionary <int, ImageMeta>(); for (int i = 0; i < t.Rows.Count; i++) { if (!sidAll.ContainsKey(Convert.ToInt32(t.Rows[i][0]))) { sidAll.Add(Convert.ToInt32(t.Rows[i][0]), new ImageMeta() { FileStoreId = t.Rows[i][1].ToString(), InfraConID = Convert.ToInt32(t.Rows[i][2]) }); } } if (sidAll.ContainsKey((int)request.ImageInfo.ImageQuality)) { request.ImageInfo.FileStoreId = sidAll[(int)request.ImageInfo.ImageQuality].FileStoreId; request.ImageInfo.InfraConID = sidAll[(int)request.ImageInfo.ImageQuality].InfraConID; } else { request.ImageInfo.FileStoreId = sidAll[(int)ImageQuality.original].FileStoreId; request.ImageInfo.InfraConID = sidAll[(int)ImageQuality.original].InfraConID; } fb = ebConnectionFactory.FilesDB.DownloadFileById(request.ImageInfo.FileStoreId, request.ImageInfo.FileCategory, request.ImageInfo.InfraConID); if (fb != null) { EbFile.Bytea_ToFile(fb, sFilePath); } } if (File.Exists(sFilePath)) { ms = new MemoryStream(File.ReadAllBytes(sFilePath)); dfs.StreamWrapper = new MemorystreamWrapper(ms); dfs.FileDetails = new FileMeta { FileName = request.ImageInfo.FileName, FileType = request.ImageInfo.FileType, Length = request.ImageInfo.Length, FileStoreId = request.ImageInfo.FileStoreId, UploadDateTime = request.ImageInfo.UploadDateTime, MetaDataDictionary = (request.ImageInfo.MetaDataDictionary != null) ? request.ImageInfo.MetaDataDictionary : new Dictionary <String, List <string> >() { }, }; } else { throw new Exception("File Not Found"); } } catch (FormatException e) { Console.WriteLine("ObjectId not in Correct Format: " + request.ImageInfo.FileName); Console.WriteLine("Exception: " + e.ToString()); } catch (Exception e) { Log.Info("Exception:" + e.ToString()); } return(dfs); }
public override void SendNotification(EbWebForm _this, EbConnectionFactory ConnFactory, Service service, FG_Root globals, ref int resp) { IDatabase DataDB = ConnFactory.DataDB; string message = "Notification from " + _this.DisplayName; if (!string.IsNullOrEmpty(this.Message?.Code)) { object msg = _this.ExecuteCSharpScriptNew(this.Message.Code, globals); message = msg.ToString(); } List <Param> plist = new List <Param> { { new Param { Name = "id", Type = ((int)EbDbTypes.Int32).ToString(), Value = _this.TableRowId.ToString() } } }; string _params = JsonConvert.SerializeObject(plist).ToBase64(); string link = $"/WebForm/Index?_r={_this.RefId}&_p={_params}&_m=1"; if (this.NotifyBy == EbFnSys_NotifyBy.Roles) { try { NotifyByUserRoleResponse result = service.Gateway.Send <NotifyByUserRoleResponse>(new NotifyByUserRoleRequest { Link = link, Title = message, RoleID = this.Roles }); } catch (Exception ex) { string temp = $"Exception when tried to send EbFnSys_NotifyBy.Roles\n Message: ${ex.Message} \nLink: ${link} \nTitle: ${message} \nRolesId: ${(this?.Roles == null ? "null" : string.Join(",", this.Roles))} \nStackTrace: ${ex.StackTrace}"; //Console.WriteLine(temp); throw new FormException($"Unable to process notification.", (int)HttpStatusCode.InternalServerError, ex.Message, temp); } resp++; } else if (this.NotifyBy == EbFnSys_NotifyBy.UserGroup) { try { NotifyByUserGroupResponse result = service.Gateway.Send <NotifyByUserGroupResponse>(new NotifyByUserGroupRequest { Link = link, Title = message, GroupId = new List <int> { this.UserGroup } }); } catch (Exception ex) { string temp = $"Exception when tried to send EbFnSys_NotifyBy.UserGroup\n Message: ${ex.Message} \nLink: ${link} \nTitle: ${message} \nGroupId: ${this.UserGroup} \nStackTrace: ${ex.StackTrace}"; //Console.WriteLine(temp); throw new FormException($"Unable to process notification.", (int)HttpStatusCode.InternalServerError, ex.Message, temp); } resp++; } else if (this.NotifyBy == EbFnSys_NotifyBy.Users) { DbParameter[] _p = this.GetParameters(_this, ConnFactory.DataDB, this.QryParams); List <int> uids = new List <int>(); EbDataTable dt = DataDB.DoQuery(this.Users.Code, _p); foreach (EbDataRow dr in dt.Rows) { int.TryParse(dr[0].ToString(), out int temp); if (!uids.Contains(temp)) { uids.Add(temp); } } foreach (int uid in uids) { try { NotifyByUserIDResponse result = service.Gateway.Send <NotifyByUserIDResponse>(new NotifyByUserIDRequest { Link = link, Title = message, UsersID = uid, User_AuthId = _this.UserObj.AuthId }); } catch (Exception ex) { string temp = $"Exception when tried to send EbFnSys_NotifyBy.Users\n Message: ${ex.Message} \nLink: ${link} \nTitle: ${message} \nUserId: ${uid} \nStackTrace: ${ex.StackTrace}"; Console.WriteLine("NotifyByUserIDRequest Inner Exception 1" + ex.InnerException?.Message + ex.InnerException?.StackTrace); Console.WriteLine("NotifyByUserIDRequest Inner Exception 2 " + ex.InnerException?.InnerException?.Message + ex.InnerException?.InnerException?.StackTrace); throw new FormException($"Unable to process notification.", (int)HttpStatusCode.InternalServerError, ex.Message, temp); } } if (uids.Count > 0) { resp++; } } }
public static DataSourceDataSetResponse ExecuteDataset(string RefId, int UserId, List <Param> Params, EbConnectionFactory ebConnectionFactory, IRedisClient Redis) { DataSourceDataSetResponse resp = new DataSourceDataSetResponse(); resp.Columns = new List <ColumnColletion>(); string _sql = string.Empty; try { EbDataReader _ds = Redis.Get <EbDataReader>(RefId); if (_ds == null) { List <EbObjectWrapper> result = EbObjectsHelper.GetParticularVersion(ebConnectionFactory.ObjectsDB, RefId); _ds = EbSerializers.Json_Deserialize(result[0].Json); if (_ds == null) { resp.ResponseStatus = new ResponseStatus { Message = "DataReader is null.... RefId: " + RefId }; return(resp); } Redis.Set <EbDataReader>(RefId, _ds); } if (_ds.FilterDialogRefId != string.Empty && _ds.FilterDialogRefId != null) { EbFilterDialog _dsf = Redis.Get <EbFilterDialog>(_ds.FilterDialogRefId); if (_dsf == null) { List <EbObjectWrapper> result = EbObjectsHelper.GetParticularVersion(ebConnectionFactory.ObjectsDB, _ds.FilterDialogRefId); _dsf = EbSerializers.Json_Deserialize(result[0].Json); Redis.Set <EbFilterDialog>(_ds.FilterDialogRefId, _dsf); } if (Params == null) { Params = _dsf.GetDefaultParams(); } } IDatabase MyDataStore = _ds.GetDatastore(ebConnectionFactory); if (_ds != null) { string _c = string.Empty; _sql = _ds.Sql; } try { IEnumerable <DbParameter> parameters = DataHelper.GetParams(MyDataStore, false, Params, 0, 0); resp.DataSet = MyDataStore.DoQueries(_sql, parameters.ToArray <System.Data.Common.DbParameter>()); foreach (EbDataTable dt in resp.DataSet.Tables) { resp.Columns.Add(dt.Columns); } //if (GetLogEnabled(RefId)) //{ // TimeSpan T = resp.DataSet.EndTime - resp.DataSet.StartTime; // InsertExecutionLog(resp.DataSet.RowNumbers, T, resp.DataSet.StartTime, UserId, Params, RefId); //} } catch (Exception e) { resp.ResponseStatus = new ResponseStatus { Message = e.Message }; Console.WriteLine("DataSourceDataSetResponse------" + e.StackTrace); Console.WriteLine("DataSourceDataSetResponse------" + e.Message); } } catch (Exception e) { Console.WriteLine(e.Message + "\n" + e.StackTrace); } return(resp); }
public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request) { var objret = base.Authenticate(authService, session, request); // no need if email present change to email if (!string.IsNullOrEmpty(session.ProviderOAuthAccess[0].DisplayName)) { EbConnectionFactory InfraConnectionFactory = authService.ResolveService <IEbConnectionFactory>() as EbConnectionFactory; if (!string.IsNullOrEmpty(session.ProviderOAuthAccess[0].Email)) { string b = string.Empty; try { bool unique = false; string sql1 = "SELECT id, pwd FROM eb_tenants WHERE email ~* @email"; DbParameter[] parameters2 = { InfraConnectionFactory.DataDB.GetNewParameter("email", EbDbTypes.String, session.ProviderOAuthAccess[0].Email) }; EbDataTable dt = InfraConnectionFactory.DataDB.DoQuery(sql1, parameters2); if (dt.Rows.Count > 0) { unique = false; } else { unique = true; } //string sql11 = "SELECT id, pwd FROM eb_tenants WHERE email ~* @email"; //DbParameter[] parameters22 = { InfraConnectionFactory.DataDB.GetNewParameter("email", EbDbTypes.String, session.ProviderOAuthAccess[0].Email) }; //int dtq = InfraConnectionFactory.DataDB.DoNonQuery(sql11, parameters22); if (unique == true) { DbParameter[] parameter1 = { InfraConnectionFactory.DataDB.GetNewParameter("email", EbDbTypes.String, session.ProviderOAuthAccess[0].Email), InfraConnectionFactory.DataDB.GetNewParameter("name", EbDbTypes.String, session.ProviderOAuthAccess[0].UserName), InfraConnectionFactory.DataDB.GetNewParameter("twitterid", EbDbTypes.String, (session.ProviderOAuthAccess[0].UserId).ToString()), InfraConnectionFactory.DataDB.GetNewParameter("password", EbDbTypes.String, (session.ProviderOAuthAccess[0].UserId.ToString() + session.ProviderOAuthAccess[0].Email.ToString()).ToMD5Hash()), }; EbDataTable dtbl = InfraConnectionFactory.DataDB.DoQuery(@"INSERT INTO eb_tenants (email,fullname,twitter_id,pwd) VALUES (:email,:name,:twitterid,:password) RETURNING id;", parameter1); } SocialSignup sco_signup = new SocialSignup { AuthProvider = session.ProviderOAuthAccess[0].Provider, Country = session.ProviderOAuthAccess[0].Country, Email = session.ProviderOAuthAccess[0].Email, Social_id = (session.ProviderOAuthAccess[0].UserId).ToString(), Fullname = session.ProviderOAuthAccess[0].UserName, //IsVerified = session.IsAuthenticated, Pauto = (session.ProviderOAuthAccess[0].UserId.ToString() + session.ProviderOAuthAccess[0].Email.ToString()).ToMD5Hash(), UniqueEmail = unique, }; b = JsonConvert.SerializeObject(sco_signup); return(authService.Redirect(SuccessRedirectUrlFilter(this, string.Format("http://*****:*****@email, @firstname,@socialid,@prolink) ON CONFLICT(socialid) DO UPDATE SET loginattempts = eb_users.loginattempts + EXCLUDED.loginattempts RETURNING eb_users.loginattempts"); // cmd.Parameters.Add(_InfraDb.DataDB.GetNewParameter("email", EbDbTypes.String, session.ProviderOAuthAccess[0].Email)); // cmd.Parameters.Add(_InfraDb.DataDB.GetNewParameter("firstname", EbDbTypes.String, session.ProviderOAuthAccess[0].DisplayName)); // cmd.Parameters.Add(_InfraDb.DataDB.GetNewParameter("socialid", EbDbTypes.String, session.ProviderOAuthAccess[0].UserName)); // cmd.Parameters.Add(_InfraDb.DataDB.GetNewParameter("prolink", EbDbTypes.String, session.ProviderOAuthAccess[0].Items["profileUrl"])); // cmd.ExecuteNonQuery(); //} //(session as CustomUserSession).Company = CoreConstants.EXPRESSBASE; //(session as CustomUserSession).WhichConsole = "tc"; //return authService.Redirect(SuccessRedirectUrlFilter(this, "http://localhost:5000/Ext/AfterSignInSocial?email=" + session.Email + "&socialId=" + session.UserName + "&provider=" + session.AuthProvider + "&providerToken=" + session.ProviderOAuthAccess[0].AccessTokenSecret)); } return(objret); }
public override void SendNotification(EbWebForm _this, EbConnectionFactory ConnFactory, Service service, FG_Root globals, ref int resp) { if (ConnFactory.MobileAppConnection == null) { return; } List <int> uids = new List <int>(); if (this.IsDirectNotification) { uids.Add(this.NotifyUserId); } else { string Qry = null; DbParameter[] _p = null; if (this.NotifyBy == EbFnSys_NotifyBy.Roles) { Qry = $"SELECT user_id FROM eb_role2user WHERE role_id = ANY(STRING_TO_ARRAY('{this.Roles.Join(",")}'::TEXT, ',')::INT[]) AND COALESCE(eb_del, 'F') = 'F'; "; } else if (this.NotifyBy == EbFnSys_NotifyBy.UserGroup) { Qry = $"SELECT userid FROM eb_user2usergroup WHERE groupid = {this.UserGroup} AND COALESCE(eb_del, 'F') = 'F'; "; } else if (this.NotifyBy == EbFnSys_NotifyBy.Users) { Qry = this.Users.Code; _p = this.GetParameters(_this, ConnFactory.DataDB, this.QryParams); } if (!string.IsNullOrWhiteSpace(Qry)) { EbDataTable dt; if (_p == null) { dt = ConnFactory.DataDB.DoQuery(Qry); } else { dt = ConnFactory.DataDB.DoQuery(Qry, _p); } foreach (EbDataRow dr in dt.Rows) { int.TryParse(dr[0].ToString(), out int temp); if (!uids.Contains(temp)) { uids.Add(temp); } } if (uids.Count == 0) { return; } this.ProcessedMsgTitle = _this.DisplayName; if (!string.IsNullOrEmpty(this.MessageTitle?.Code)) { object msg = _this.ExecuteCSharpScriptNew(this.MessageTitle.Code, globals); this.ProcessedMsgTitle = msg.ToString(); } this.ProcessedMessage = string.Empty; if (!string.IsNullOrEmpty(this.Message?.Code)) { object msg = _this.ExecuteCSharpScriptNew(this.Message.Code, globals); this.ProcessedMessage = msg.ToString(); } } } if (uids.Count > 0) { List <string> userAuthIds = new List <string>(); EbNFData Data = new EbNFData() { Title = this.ProcessedMsgTitle, Message = this.ProcessedMessage }; EbAzureNFClient client = EbAzureNFClient.Create(ConnFactory.MobileAppConnection); foreach (int uid in uids) { userAuthIds.Add(client.ConvertToAuthTag(_this.SolutionObj.SolutionID + CharConstants.COLON + uid + CharConstants.COLON + TokenConstants.MC)); } EbNFRequest req = new EbNFRequest() { Platform = PNSPlatforms.GCM, Tags = userAuthIds }; req.SetPayload(new EbNFDataTemplateAndroid() { Data = Data }); try { client.Send(req); } catch (Exception ex) { string temp = $"Exception when tried to send EbFnMobile\n Message: ${ex.Message} \nStackTrace: ${ex.StackTrace}"; throw new FormException($"Unable to process notification.", (int)HttpStatusCode.InternalServerError, ex.Message, temp); } resp++; } }
public bool Post(SlackPostRequest req) { string sql = "SELECT slackjson FROM eb_users WHERE id = @id"; EbConnectionFactory dbFactory = new EbConnectionFactory(req.SolnId, this.Redis); try { var dt = dbFactory.DataDB.DoQuery(sql, new DbParameter[] { dbFactory.DataDB.GetNewParameter("id", EbDbTypes.Int32, req.UserId) }); var json = dt.Rows[0][0]; SlackJson slackJson = JsonConvert.DeserializeObject <SlackJson>(json.ToString()); var client = new RestClient("https://slack.com"); if (req.PostType == 1) { var request = new RestRequest("api/files.upload", Method.POST); request.AddParameter("token", slackJson.AccessToken); request.AddParameter("user_id", slackJson.UserId); request.AddParameter("team_id", slackJson.TeamId); request.AddParameter("channels", req.Payload.Channel); if (!string.IsNullOrEmpty(req.Payload.Text)) { request.AddParameter("content", req.Payload.Text); } if (req.Payload.SlackFile != null && req.Payload.SlackFile.FileByte != null && req.Payload.SlackFile.FileByte.Length > 0) { request.AddFile("file", req.Payload.SlackFile.FileByte, req.Payload.SlackFile.FileName, contentType: "multipart/form-data"); } //Execute the request var res = client.ExecuteAsyncPost(request, SlackCallBack, "POST"); } else if (req.PostType == 0) { var request = new RestRequest("api/chat.postMessage", Method.POST); request.AddParameter("token", slackJson.AccessToken); request.AddParameter("channels", req.Payload.Channel); request.AddParameter("user_id", slackJson.UserId); request.AddParameter("team_id", slackJson.TeamId); if (!string.IsNullOrEmpty(req.Payload.Text)) { request.AddParameter("text", req.Payload.Text); } //Execute the request var res = client.ExecuteAsyncPost(request, SlackCallBack, "POST"); } } catch (Exception e) { Log.Info("Exception: " + e.Message.ToString()); return(false); } return(true); }
public virtual void SendNotification(EbWebForm _this, EbConnectionFactory ConnFactory, Service service, FG_Root globals, ref int resp) { }
public int PersistIntegrationConf(string Sol_Id, EbConnectionFactory infra, int UserId) { int nid = 0; string query = string.Empty; string json = EbSerializers.Json_Serialize(this);// JsonConvert.SerializeObject(this); DbParameter[] parameters = { infra.DataDB.GetNewParameter("solution_id", EbDbTypes.String, Sol_Id), infra.DataDB.GetNewParameter("nick_name", EbDbTypes.String, !(string.IsNullOrEmpty(this.NickName))?this.NickName:string.Empty), infra.DataDB.GetNewParameter("type", EbDbTypes.String, this.Type.ToString()), infra.DataDB.GetNewParameter("con_obj", EbDbTypes.Json, json), infra.DataDB.GetNewParameter("uid", EbDbTypes.Int32, UserId), infra.DataDB.GetNewParameter("id", EbDbTypes.Int32, this.Id) }; if (this.Id <= 0) { query = @" INSERT INTO eb_integration_configs (solution_id, nickname, type, con_obj, created_by, created_at, eb_del) VALUES (@solution_id, @nick_name, @type, @con_obj, @uid, NOW() , 'F') RETURNING id;"; EbDataSet ds = infra.DataDB.DoQueries(query, parameters); nid = Convert.ToInt32(ds.Tables[0].Rows[0][0]); } else { query = @" UPDATE eb_integration_configs SET modified_at = NOW(), modified_by = @uid, eb_del = 'T' WHERE id = @id; INSERT INTO eb_integration_configs (solution_id, nickname, type, con_obj, created_by, created_at, eb_del) VALUES (@solution_id, @nick_name, @type, @con_obj, @uid, NOW() , 'F') RETURNING id;"; EbDataSet ds = infra.DataDB.DoQueries(query, parameters); nid = Convert.ToInt32(ds.Tables[0].Rows[0][0]); if (this.Id != 0) { query = @"UPDATE eb_integrations SET eb_integration_conf_id = @nid WHERE eb_integration_conf_id = @oid; "; DbParameter[] parameter = { infra.DataDB.GetNewParameter("nid", EbDbTypes.Int32, nid), infra.DataDB.GetNewParameter("oid", EbDbTypes.Int32, this.Id) }; infra.DataDB.DoNonQuery(query, parameter); } } return(nid); }
//Send my actions push notifications public static async Task <EbNFResponse> SendMobileNotification(EbWebForm _this, EbConnectionFactory ConnFactory, Service service) { EbNFResponse resp = new EbNFResponse("0"); try { if (_this.MyActNotification?.SendPushNotification == true && ConnFactory.MobileAppConnection != null) { List <int> userIds = new List <int>(); if (_this.MyActNotification.ApproverEntity == ApproverEntityTypes.Users) { userIds = _this.MyActNotification.UserIds; } else if (_this.MyActNotification.ApproverEntity == ApproverEntityTypes.Role || _this.MyActNotification.ApproverEntity == ApproverEntityTypes.DynamicRole || _this.MyActNotification.ApproverEntity == ApproverEntityTypes.UserGroup) { string Qry; if (_this.MyActNotification.ApproverEntity == ApproverEntityTypes.UserGroup) { Qry = $"SELECT userid FROM eb_user2usergroup WHERE groupid = {_this.MyActNotification.UserGroupId} AND COALESCE(eb_del, 'F') = 'F'; "; } else// static/dynamic role { Qry = $"SELECT user_id FROM eb_role2user WHERE role_id = ANY(STRING_TO_ARRAY('{_this.MyActNotification.RoleIds.Join(",")}'::TEXT, ',')::INT[]) AND COALESCE(eb_del, 'F') = 'F'; "; } EbDataTable dt = ConnFactory.DataDB.DoQuery(Qry); foreach (EbDataRow dr in dt.Rows) { int.TryParse(dr[0].ToString(), out int temp); if (!userIds.Contains(temp)) { userIds.Add(temp); } } } else { throw new Exception("Invalid approver entity: " + _this.MyActNotification.ApproverEntity); } if (userIds.Count == 0) { throw new Exception("User Id collection is empty"); } List <string> userAuthIds = new List <string>(); EbNFData Data = new EbNFData() { Title = _this.MyActNotification.Title, Message = _this.MyActNotification.Description, Link = new EbNFLink() { LinkType = EbNFLinkTypes.Action, ActionId = _this.MyActNotification.MyActionId } }; EbAzureNFClient client = EbAzureNFClient.Create(ConnFactory.MobileAppConnection); foreach (int uid in userIds) { string authId = _this.SolutionObj.SolutionID + CharConstants.COLON + uid + CharConstants.COLON + TokenConstants.MC; User user = service.Redis.Get <User>(authId); if (user != null) { if (user.LocationIds.Contains(-1) || user.LocationIds.Contains(_this.LocationId)) { userAuthIds.Add(client.ConvertToAuthTag(authId)); } } } if (userAuthIds.Count > 0) { EbNFRequest req = new EbNFRequest() { Platform = PNSPlatforms.GCM, Tags = userAuthIds }; req.SetPayload(new EbNFDataTemplateAndroid() { Data = Data }); resp = await client.Send(req); } } } catch (Exception ex) { resp.Message = ex.Message; Console.WriteLine("Exception in SendMobileNotification: " + ex.Message); } Console.WriteLine("SendMobileNotification response: " + resp.Message); return(resp); }