├── .gitignore ├── 07558_centurygothic.ttf ├── 123_meera.ttf ├── AksharUnicode.ttf ├── AssemblyInfo.cs ├── Auth0 ├── EbApiAuthProvider.cs ├── EbRegistrationService.cs ├── GetAccessTokenService.cs ├── JsonWebToken.cs ├── MyApiKeyAuthProvider.cs ├── MyCredentialsAuthProvider.cs ├── MyFacebookAuthProvider.cs ├── MyGithubAuthProvider.cs ├── MyGoogleAuthProvider.cs ├── MyLinkedInAuthProvider.cs └── MyTwitterAuthProvider.cs ├── ExpressBase.ServiceStack.csproj ├── LICENSE ├── MQServices ├── ApiService.cs ├── EmailService.cs ├── ExportToExcelService.cs ├── ImportExportService.cs ├── PdfToEmailService.cs ├── RefreshSolutionConnections.cs ├── RefreshSolutionIdMap.cs ├── ReportService.cs ├── SMSService.cs ├── SlackService.cs └── SqlJobService.cs ├── NotoSerifMalayalam-VariableFont_wght.ttf ├── Program.cs ├── Properties └── launchSettings.json ├── README.md ├── Services ├── ApiConversionService.cs ├── ApiServices.cs ├── AppStoreService.cs ├── CalendarService.cs ├── ChatbotServices.cs ├── DataSourceServices.cs ├── DataVisService.cs ├── DbClientServices.cs ├── DevRelatedServices.cs ├── EbBluePrintServices.cs ├── EbFileDownloadService.cs ├── EbMeetingService.cs ├── EbMeetingServices.cs ├── ExcelServices.cs ├── FileOperationServices.cs ├── FilterDialogService.cs ├── FormPersistServices.cs ├── GoogleMapServices.cs ├── IoTService.cs ├── LeadManagementService.cs ├── MenuServices.cs ├── MobileServices.cs ├── MultiLanguageService.cs ├── NotificationService.cs ├── PayPalService.cs ├── ProductionDBManagerServices.cs ├── ProfilerServices.cs ├── RedisClientServices.cs ├── ReportService.cs ├── ResetPasswordService.cs ├── SchedulerServices.cs ├── SecurityServices.cs ├── ServerEventsServices.cs ├── SqlJobServices.cs ├── StripeService.cs ├── StudioServices.cs ├── SupportServices.cs ├── SurveyServices.cs ├── TenantUserServices.cs ├── Test.cs ├── TwoFactorAuthServices.cs ├── VrgsTestService.cs └── WebFormServices.cs ├── Startup.cs ├── Tenant Services ├── ConnectionManagerService.cs ├── EbDbCreateServices.cs ├── InfraServices.cs └── WikiService.cs └── robots.txt /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | artifacts/ 46 | 47 | *_i.c 48 | *_p.c 49 | *_i.h 50 | *.ilk 51 | *.meta 52 | *.obj 53 | *.pch 54 | *.pdb 55 | *.pgc 56 | *.pgd 57 | *.rsp 58 | *.sbr 59 | *.tlb 60 | *.tli 61 | *.tlh 62 | *.tmp 63 | *.tmp_proj 64 | *.log 65 | *.vspscc 66 | *.vssscc 67 | .builds 68 | *.pidb 69 | *.svclog 70 | *.scc 71 | 72 | # Chutzpah Test files 73 | _Chutzpah* 74 | 75 | # Visual C++ cache files 76 | ipch/ 77 | *.aps 78 | *.ncb 79 | *.opendb 80 | *.opensdf 81 | *.sdf 82 | *.cachefile 83 | *.VC.db 84 | *.VC.VC.opendb 85 | 86 | # Visual Studio profiler 87 | *.psess 88 | *.vsp 89 | *.vspx 90 | *.sap 91 | 92 | # TFS 2012 Local Workspace 93 | $tf/ 94 | 95 | # Guidance Automation Toolkit 96 | *.gpState 97 | 98 | # ReSharper is a .NET coding add-in 99 | _ReSharper*/ 100 | *.[Rr]e[Ss]harper 101 | *.DotSettings.user 102 | 103 | # JustCode is a .NET coding add-in 104 | .JustCode 105 | 106 | # TeamCity is a build add-in 107 | _TeamCity* 108 | 109 | # DotCover is a Code Coverage Tool 110 | *.dotCover 111 | 112 | # NCrunch 113 | _NCrunch_* 114 | .*crunch*.local.xml 115 | nCrunchTemp_* 116 | 117 | # MightyMoose 118 | *.mm.* 119 | AutoTest.Net/ 120 | 121 | # Web workbench (sass) 122 | .sass-cache/ 123 | 124 | # Installshield output folder 125 | [Ee]xpress/ 126 | 127 | # DocProject is a documentation generator add-in 128 | DocProject/buildhelp/ 129 | DocProject/Help/*.HxT 130 | DocProject/Help/*.HxC 131 | DocProject/Help/*.hhc 132 | DocProject/Help/*.hhk 133 | DocProject/Help/*.hhp 134 | DocProject/Help/Html2 135 | DocProject/Help/html 136 | 137 | # Click-Once directory 138 | publish/ 139 | 140 | # Publish Web Output 141 | *.[Pp]ublish.xml 142 | *.azurePubxml 143 | # TODO: Comment the next line if you want to checkin your web deploy settings 144 | # but database connection strings (with potential passwords) will be unencrypted 145 | *.pubxml 146 | *.publishproj 147 | 148 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 149 | # checkin your Azure Web App publish settings, but sensitive information contained 150 | # in these scripts will be unencrypted 151 | PublishScripts/ 152 | 153 | # NuGet Packages 154 | *.nupkg 155 | # The packages folder can be ignored because of Package Restore 156 | **/packages/* 157 | # except build/, which is used as an MSBuild target. 158 | !**/packages/build/ 159 | # Uncomment if necessary however generally it will be regenerated when needed 160 | #!**/packages/repositories.config 161 | # NuGet v3's project.json files produces more ignoreable files 162 | *.nuget.props 163 | *.nuget.targets 164 | 165 | # Microsoft Azure Build Output 166 | csx/ 167 | *.build.csdef 168 | 169 | # Microsoft Azure Emulator 170 | ecf/ 171 | rcf/ 172 | 173 | # Windows Store app package directories and files 174 | AppPackages/ 175 | BundleArtifacts/ 176 | Package.StoreAssociation.xml 177 | _pkginfo.txt 178 | 179 | # Visual Studio cache files 180 | # files ending in .cache can be ignored 181 | *.[Cc]ache 182 | # but keep track of directories ending in .cache 183 | !*.[Cc]ache/ 184 | 185 | # Others 186 | ClientBin/ 187 | ~$* 188 | *~ 189 | *.dbmdl 190 | *.dbproj.schemaview 191 | *.pfx 192 | *.publishsettings 193 | node_modules/ 194 | orleans.codegen.cs 195 | 196 | # Since there are multiple workflows, uncomment next line to ignore bower_components 197 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 198 | #bower_components/ 199 | 200 | # RIA/Silverlight projects 201 | Generated_Code/ 202 | 203 | # Backup & report files from converting an old project file 204 | # to a newer Visual Studio version. Backup files are not needed, 205 | # because we have git ;-) 206 | _UpgradeReport_Files/ 207 | Backup*/ 208 | UpgradeLog*.XML 209 | UpgradeLog*.htm 210 | 211 | # SQL Server files 212 | *.mdf 213 | *.ldf 214 | 215 | # Business Intelligence projects 216 | *.rdl.data 217 | *.bim.layout 218 | *.bim_*.settings 219 | 220 | # Microsoft Fakes 221 | FakesAssemblies/ 222 | 223 | # GhostDoc plugin setting file 224 | *.GhostDoc.xml 225 | 226 | # Node.js Tools for Visual Studio 227 | .ntvs_analysis.dat 228 | 229 | # Visual Studio 6 build log 230 | *.plg 231 | 232 | # Visual Studio 6 workspace options file 233 | *.opt 234 | 235 | # Visual Studio LightSwitch build output 236 | **/*.HTMLClient/GeneratedArtifacts 237 | **/*.DesktopClient/GeneratedArtifacts 238 | **/*.DesktopClient/ModelManifest.xml 239 | **/*.Server/GeneratedArtifacts 240 | **/*.Server/ModelManifest.xml 241 | _Pvt_Extensions 242 | 243 | # Paket dependency manager 244 | .paket/paket.exe 245 | paket-files/ 246 | 247 | # FAKE - F# Make 248 | .fake/ 249 | 250 | # JetBrains Rider 251 | .idea/ 252 | *.sln.iml 253 | *.ps1 254 | /Properties/PublishProfiles/publish-module.psm1 255 | -------------------------------------------------------------------------------- /07558_centurygothic.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ExpressBaseSystems/ExpressBase.ServiceStack/60e079fd6928986f90583fdab994815594e4d969/07558_centurygothic.ttf -------------------------------------------------------------------------------- /123_meera.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ExpressBaseSystems/ExpressBase.ServiceStack/60e079fd6928986f90583fdab994815594e4d969/123_meera.ttf -------------------------------------------------------------------------------- /AksharUnicode.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ExpressBaseSystems/ExpressBase.ServiceStack/60e079fd6928986f90583fdab994815594e4d969/AksharUnicode.ttf -------------------------------------------------------------------------------- /AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | 3 | [assembly: AssemblyVersion("1.0.*")] 4 | -------------------------------------------------------------------------------- /Auth0/EbApiAuthProvider.cs: -------------------------------------------------------------------------------- 1 | using ExpressBase.Common.Constants; 2 | using ExpressBase.Common.ServiceStack.Auth; 3 | using ExpressBase.Security; 4 | using ServiceStack; 5 | using ServiceStack.Auth; 6 | using ServiceStack.Configuration; 7 | using ServiceStack.Redis; 8 | using ServiceStack.Web; 9 | using System; 10 | using System.Collections.Generic; 11 | using System.Text; 12 | 13 | namespace ExpressBase.ServiceStack.Auth0 14 | { 15 | public class EbApiAuthProvider : ApiKeyAuthProvider 16 | { 17 | public EbApiAuthProvider(IAppSettings appSettings) : base(appSettings) 18 | { 19 | } 20 | 21 | public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request) 22 | { 23 | var authRepo = HostContext.AppHost.GetAuthRepository(authService.Request); 24 | using (authRepo as IDisposable) 25 | { 26 | var apiKey = GetApiKey(authService.Request, request.Password); 27 | ValidateApiKey(apiKey); 28 | 29 | var userAuth = authRepo.GetUserAuth(apiKey.UserAuthId); 30 | if (userAuth == null) 31 | throw HttpError.Unauthorized("User for ApiKey does not exist"); 32 | 33 | if (IsAccountLocked(authRepo, userAuth)) 34 | throw new AuthenticationException(ErrorMessages.UserAccountLocked.Localize(authService.Request)); 35 | 36 | PopulateSession(authRepo as IUserAuthRepository, userAuth, (session as CustomUserSession), apiKey.UserAuthId); 37 | 38 | if (session.UserAuthName == null) 39 | session.UserAuthName = userAuth.UserName ?? userAuth.Email; 40 | 41 | var response = OnAuthenticated(authService, session, null, null); 42 | if (response != null) 43 | return response; 44 | 45 | authService.Request.Items[Keywords.ApiKey] = apiKey; 46 | 47 | return new AuthenticateResponse 48 | { 49 | UserId = session.UserAuthId, 50 | UserName = session.UserName, 51 | SessionId = session.Id, 52 | DisplayName = session.DisplayName 53 | ?? session.UserName 54 | ?? $"{session.FirstName} {session.LastName}".Trim(), 55 | ReferrerUrl = request.Continue, 56 | }; 57 | } 58 | } 59 | 60 | public override string CreateApiKey(string environment, string keyType, int sizeBytes) 61 | { 62 | return base.CreateApiKey(environment, keyType, sizeBytes); 63 | } 64 | 65 | public override bool IsAuthorized(IAuthSession session, IAuthTokens tokens, Authenticate request = null) 66 | { 67 | return base.IsAuthorized(session, tokens, request); 68 | } 69 | 70 | public override IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary authInfo) 71 | { 72 | return base.OnAuthenticated(authService, session, tokens, authInfo); 73 | } 74 | 75 | public override void OnFailedAuthentication(IAuthSession session, IRequest httpReq, IResponse httpRes) 76 | { 77 | base.OnFailedAuthentication(session, httpReq, httpRes); 78 | } 79 | 80 | protected override ApiKey GetApiKey(IRequest req, string apiKey) 81 | { 82 | return base.GetApiKey(req, apiKey); 83 | } 84 | 85 | protected override IAuthRepository GetAuthRepository(IRequest req) 86 | { 87 | return base.GetAuthRepository(req); 88 | } 89 | 90 | protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary authInfo) 91 | { 92 | base.LoadUserAuthInfo(userSession, tokens, authInfo); 93 | } 94 | 95 | protected override void ValidateApiKey(ApiKey apiKey) 96 | { 97 | base.ValidateApiKey(apiKey); 98 | } 99 | 100 | public void PopulateSession(IUserAuthRepository authRepo, IUserAuth userAuth, CustomUserSession session, string userId) 101 | { 102 | if (authRepo == null) 103 | return; 104 | 105 | var holdSessionId = session.Id; 106 | session.PopulateWith(userAuth); //overwrites session.Id 107 | session.Id = holdSessionId; 108 | session.IsAuthenticated = true; 109 | session.UserAuthId = userId; 110 | 111 | string temp = userId.Substring(userId.IndexOf(CharConstants.COLON) + 1); 112 | session.Email = temp.Substring(0, temp.IndexOf(CharConstants.COLON)); 113 | session.Uid = (userAuth as User).UserId; 114 | session.WhichConsole = userId.Substring(userId.Length - 2); 115 | session.Roles.Clear(); 116 | session.Permissions.Clear(); 117 | } 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /Auth0/EbRegistrationService.cs: -------------------------------------------------------------------------------- 1 | using ExpressBase.Common; 2 | using ExpressBase.Common.Data; 3 | using ExpressBase.Common.Extensions; 4 | using ExpressBase.Common.Structures; 5 | using ExpressBase.Objects.ServiceStack_Artifacts; 6 | using ServiceStack; 7 | using ServiceStack.Messaging; 8 | using System; 9 | using System.Data.Common; 10 | using static ExpressBase.ServiceStack.EmailService; 11 | 12 | namespace ExpressBase.ServiceStack.Auth0 13 | { 14 | public class EbRegisterService : EbBaseService 15 | { 16 | public EbRegisterService(IMessageProducer _mqp, IMessageQueueClient _mqc) : base(_mqp, _mqc) { } 17 | 18 | public RegisterResponse Post(RegisterRequest request) 19 | { 20 | RegisterResponse response = new RegisterResponse(); 21 | // var _InfraDb = base.ResolveService() as EbConnectionFactory; 22 | 23 | DbParameter[] parameters = { 24 | this.InfraConnectionFactory.DataDB.GetNewParameter("email", EbDbTypes.String, request.Email) 25 | // _InfraDb.DataDB.GetNewParameter("pwd", System.Data.DbType.String, (request.Password + request.Email).ToMD5Hash()) 26 | }; 27 | 28 | EbDataTable dt = this.InfraConnectionFactory.DataDB.DoQuery("INSERT INTO eb_tenants (email) VALUES ( @email) RETURNING id;", parameters); 29 | 30 | if (dt.Rows.Count > 0) 31 | { 32 | try 33 | { 34 | response.UserId = dt.Rows[0][0].ToString(); 35 | } 36 | catch (Exception e) 37 | { 38 | Console.WriteLine("Exception: " + e.ToString()); 39 | } 40 | } 41 | 42 | return response; 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /Auth0/GetAccessTokenService.cs: -------------------------------------------------------------------------------- 1 | using ExpressBase.Common.Constants; 2 | using ExpressBase.Common.ServiceStack.Auth; 3 | using ExpressBase.Security; 4 | using ServiceStack; 5 | using ServiceStack.Auth; 6 | using ServiceStack.Text; 7 | using System; 8 | using System.Collections.Generic; 9 | using System.Linq; 10 | using System.Threading.Tasks; 11 | 12 | namespace ExpressBase.ServiceStack.Auth0 13 | { 14 | public class EbGetAccessTokenService 15 | { 16 | [DefaultRequest(typeof(GetAccessToken))] 17 | public class GetAccessTokenService : Service 18 | { 19 | public object Any(GetAccessToken request) 20 | { 21 | var jwtAuthProvider = (MyJwtAuthProvider)AuthenticateService.GetRequiredJwtAuthProvider(); 22 | 23 | if (jwtAuthProvider.RequireSecureConnection && !Request.IsSecureConnection) 24 | throw HttpError.Forbidden(ErrorMessages.JwtRequiresSecureConnection.Localize(Request)); 25 | 26 | if (string.IsNullOrEmpty(request.RefreshToken)) 27 | throw new ArgumentNullException(nameof(request.RefreshToken)); 28 | 29 | JsonObject jwtPayload; 30 | try 31 | { 32 | jwtPayload = jwtAuthProvider.GetVerifiedJwtPayload(Request, request.RefreshToken.Split(CharConstants.DOT)); 33 | } 34 | catch (ArgumentException) 35 | { 36 | throw; 37 | } 38 | catch (Exception ex) 39 | { 40 | throw new ArgumentException(ex.Message); 41 | } 42 | 43 | jwtAuthProvider.AssertJwtPayloadIsValid(jwtPayload); 44 | 45 | if (jwtAuthProvider.ValidateRefreshToken != null && !jwtAuthProvider.ValidateRefreshToken(jwtPayload, Request)) 46 | throw new ArgumentException(ErrorMessages.RefreshTokenInvalid.Localize(Request), nameof(request.RefreshToken)); 47 | 48 | var userId = jwtPayload[TokenConstants.SUB]; 49 | 50 | CustomUserSession session; 51 | if (AuthRepository is IUserAuthRepository userRepo) 52 | { 53 | var userAuth = userRepo.GetUserAuth(userId); 54 | if (userAuth == null) 55 | throw HttpError.NotFound(ErrorMessages.UserNotExists.Localize(Request)); 56 | 57 | if (jwtAuthProvider.IsAccountLocked(userRepo, userAuth)) 58 | throw new AuthenticationException(ErrorMessages.UserAccountLocked.Localize(Request)); 59 | 60 | session = SessionFeature.CreateNewSession(Request, SessionExtensions.CreateRandomSessionId()) as CustomUserSession; 61 | PopulateSession(userRepo, userAuth, session, userId); 62 | } 63 | else 64 | throw new NotSupportedException("JWT RefreshTokens requires a registered IUserAuthRepository or an AuthProvider implementing IUserSessionSource"); 65 | 66 | var accessToken = jwtAuthProvider.CreateJwtBearerToken(Request, session); 67 | 68 | return new GetAccessTokenResponse 69 | { 70 | AccessToken = accessToken 71 | }; 72 | } 73 | 74 | public void PopulateSession(IUserAuthRepository authRepo, IUserAuth userAuth, CustomUserSession session, string userId) 75 | { 76 | if (authRepo == null) 77 | return; 78 | 79 | var holdSessionId = session.Id; 80 | session.PopulateWith(userAuth); //overwrites session.Id 81 | session.Id = holdSessionId; 82 | session.IsAuthenticated = true; 83 | session.UserAuthId = userId; 84 | 85 | // string temp = userId.Substring(userId.IndexOf(CharConstants.COLON) + 1); 86 | session.Email = userAuth.Email; ; 87 | session.Uid = (userAuth as User).UserId; 88 | session.WhichConsole = userId.Substring(userId.Length - 2); 89 | session.SourceIp = (userAuth as User).SourceIp; 90 | session.Roles.Clear(); 91 | session.Permissions.Clear(); 92 | } 93 | } 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /Auth0/JsonWebToken.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Security.Claims; 6 | using ServiceStack.Text; 7 | 8 | namespace ExpressBase.ServiceStack.Auth0 9 | { 10 | //public static class JsonWebToken 11 | //{ 12 | // private const string NameClaimType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"; 13 | // private const string RoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"; 14 | // private const string ActorClaimType = "http://schemas.xmlsoap.org/ws/2009/09/identity/claims/actor"; 15 | // private const string DefaultIssuer = "LOCAL AUTHORITY"; 16 | // private const string StringClaimValueType = "http://www.w3.org/2001/XMLSchema#string"; 17 | 18 | // // sort claim types by relevance 19 | // private static IEnumerable claimTypesForUserName = new[] { "name", "email", "user_id", "sub" }; 20 | // private static ISet claimsToExclude = new HashSet(new[] { "iss", "sub", "aud", "exp", "iat", "identities" }); 21 | 22 | // private static DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); 23 | 24 | // public static ClaimsPrincipal ValidateToken(string token, string secretKey, string audience = null, bool checkExpiration = false, string issuer = null) 25 | // { 26 | // var payloadJson = System.IdentityModel.Tokens.Jwt..Decode(token, Convert.FromBase64String(secretKey), verify: true); 27 | // var payloadData = JsonObject.Parse(payloadJson); 28 | 29 | // // audience check 30 | 31 | // if (!string.IsNullOrEmpty(audience)) 32 | // { 33 | // var aud = payloadData["aud"]; 34 | // if (!string.Equals(aud, audience, StringComparison.Ordinal)) 35 | // { 36 | // throw new TokenValidationException(string.Format("Audience mismatch. Expected: '{0}' and got: '{1}'", audience, aud)); 37 | // } 38 | // } 39 | 40 | // // expiration check 41 | 42 | // if (checkExpiration) 43 | // { 44 | // var exp = payloadData["exp"]; 45 | 46 | // if (exp != null) 47 | // { 48 | // DateTime validTo = FromUnixTime(long.Parse(exp)); 49 | // if (DateTime.Compare(validTo, DateTime.UtcNow) <= 0) 50 | // { 51 | // throw new TokenValidationException( 52 | // string.Format("Token is expired. Expiration: '{0}'. Current: '{1}'", validTo, DateTime.UtcNow)); 53 | // } 54 | // } 55 | // } 56 | 57 | // // issuer check 58 | // var iss = payloadData["iss"]; 59 | // if (iss != null) 60 | // { 61 | // if (!string.IsNullOrEmpty(issuer)) 62 | // { 63 | // if (string.Equals(iss, issuer, StringComparison.Ordinal)) 64 | // { 65 | // throw new TokenValidationException(string.Format("Token issuer mismatch. Expected: '{0}' and got: '{1}'", issuer, iss)); 66 | // } 67 | // } 68 | // else 69 | // { 70 | // // if issuer is not specified, set issuer with jwt[iss] 71 | // issuer = iss; 72 | // } 73 | // } 74 | 75 | // return new ClaimsPrincipal(ClaimsIdentityFromJwt(payloadData, issuer)); 76 | // } 77 | 78 | // private static ICollection ClaimsFromJwt(JsonObject jwtData, string issuer) 79 | // { 80 | // issuer = issuer ?? DefaultIssuer; 81 | 82 | // var list = jwtData.Where(p => !claimsToExclude.Contains(p.Key)) // don't include specific claims 83 | // .SelectMany(p => 84 | // { 85 | // if (p.Value.StartsWith("[")) 86 | // { 87 | // return jwtData.Get(p.Key).Select(v => new Claim(p.Key, v, StringClaimValueType, issuer, issuer)); 88 | // } 89 | // else if (p.Value.StartsWith("{")) 90 | // { 91 | // var claim = new Claim(p.Key, p.Value, StringClaimValueType, issuer, issuer); 92 | // var properties = jwtData.Object(p.Key).ToDictionary(); 93 | // foreach (var prop in properties) 94 | // { 95 | // claim.Properties.Add(prop); 96 | // } 97 | 98 | // return new[] { claim }; 99 | // } 100 | // else 101 | // { 102 | // return new[] { new Claim(p.Key, p.Value, StringClaimValueType, issuer, issuer) }; 103 | // } 104 | // }).ToList(); 105 | 106 | // // set claim for user name 107 | // // use original jwtData because claimsToExclude filter has sub and otherwise it wouldn't be used 108 | // var userNameClaimType = claimTypesForUserName.FirstOrDefault(ct => jwtData.ContainsKey(ct)); 109 | // if (userNameClaimType != null) 110 | // { 111 | // list.Add(new Claim(NameClaimType, jwtData[userNameClaimType].ToString(), StringClaimValueType, issuer, issuer)); 112 | // } 113 | 114 | // // set claims for roles array 115 | // list.Where(c => c.Type == "roles").ToList().ForEach(r => 116 | // { 117 | // list.Add(new Claim(RoleClaimType, r.Value, StringClaimValueType, issuer, issuer)); 118 | // }); 119 | 120 | // list.RemoveAll(c => c.Type == "roles"); 121 | 122 | // return list; 123 | // } 124 | 125 | // private static ClaimsIdentity ClaimsIdentityFromJwt(JsonObject jwtData, string issuer) 126 | // { 127 | // var subject = new ClaimsIdentity("Federation", NameClaimType, RoleClaimType); 128 | // var claims = ClaimsFromJwt(jwtData, issuer); 129 | 130 | // foreach (Claim claim in claims) 131 | // { 132 | // var type = claim.Type; 133 | // if (type == ActorClaimType) 134 | // { 135 | // if (subject.Actor != null) 136 | // { 137 | // throw new InvalidOperationException(string.Format( 138 | // "Jwt10401: Only a single 'Actor' is supported. Found second claim of type: '{0}', value: '{1}'", new object[] { "actor", claim.Value })); 139 | // } 140 | 141 | // subject.AddClaim(new Claim(type, claim.Value, claim.ValueType, issuer, issuer, subject)); 142 | 143 | // continue; 144 | // } 145 | 146 | // var newClaim = new Claim(type, claim.Value, claim.ValueType, issuer, issuer, subject); 147 | 148 | // foreach (var prop in claim.Properties) 149 | // { 150 | // newClaim.Properties.Add(prop); 151 | // } 152 | 153 | // subject.AddClaim(newClaim); 154 | // } 155 | 156 | // return subject; 157 | // } 158 | 159 | // private static DateTime FromUnixTime(long unixTime) 160 | // { 161 | // return unixEpoch.AddSeconds(unixTime); 162 | // } 163 | 164 | // public class TokenValidationException : Exception 165 | // { 166 | // public TokenValidationException(string message) 167 | // : base(message) 168 | // { 169 | // } 170 | // } 171 | //} 172 | } 173 | 174 | //https://gist.github.com/svantreeck/436f6ddddda38c735c62 175 | -------------------------------------------------------------------------------- /Auth0/MyApiKeyAuthProvider.cs: -------------------------------------------------------------------------------- 1 | //using System; 2 | //using System.Collections.Generic; 3 | //using System.Linq; 4 | //using System.Net; 5 | //using ExpressBase.Objects.ServiceStack_Artifacts; 6 | //using ServiceStack.Auth; 7 | //using ServiceStack.Configuration; 8 | //using ServiceStack.Host; 9 | //using ServiceStack.Logging; 10 | //using ServiceStack.Web; 11 | 12 | //namespace ServiceStack.Auth 13 | //{ 14 | // /// 15 | // /// The Interface Auth Repositories need to implement to support API Keys 16 | // /// 17 | // public interface IMyManageApiKeys 18 | // { 19 | // void InitApiKeySchema(); 20 | 21 | // bool ApiKeyExists(string apiKey); 22 | 23 | // MyApiKey GetApiKey(string apiKey); 24 | 25 | // List GetUserApiKeys(string userId); 26 | 27 | // void StoreAll(IEnumerable apiKeys); 28 | // } 29 | 30 | // /// 31 | // /// The POCO Table used to persist API Keys 32 | // /// 33 | // public class MyApiKey : IMeta 34 | // { 35 | // public string Id { get; set; } 36 | // public string UserAuthId { get; set; } 37 | 38 | // public string Environment { get; set; } 39 | // public string KeyType { get; set; } 40 | 41 | // public DateTime CreatedDate { get; set; } 42 | // public DateTime? ExpiryDate { get; set; } 43 | // public DateTime? CancelledDate { get; set; } 44 | // public string Notes { get; set; } 45 | 46 | // //Custom Reference Data 47 | // public int? RefId { get; set; } 48 | // public string RefIdStr { get; set; } 49 | // public Dictionary Meta { get; set; } 50 | // } 51 | 52 | // public delegate string MyCreateApiKeyDelegate(string environment, string keyType, int keySizeBytes); 53 | 54 | // /// 55 | // /// Enable access to protected Services using API Keys 56 | // /// 57 | // public class MyApiKeyAuthProvider : ApiKeyAuthProvider 58 | // { 59 | // public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request) 60 | // { 61 | // ILog log = LogManager.GetLogger(GetType()); 62 | 63 | // log.Info("In Authenticate method1"); 64 | // AuthenticateResponse authResponse = base.Authenticate(authService, session, request) as AuthenticateResponse; 65 | 66 | // log.Info("In Authenticate method2"); 67 | // var _customUserSession = authService.GetSession() as CustomUserSession; 68 | 69 | // log.Info("In Authenticate method3"); 70 | // return new MyAuthenticateResponse 71 | // { 72 | // User = _customUserSession.User 73 | // }; 74 | // } 75 | // } 76 | 77 | //} -------------------------------------------------------------------------------- /Auth0/MyCredentialsAuthProvider.cs: -------------------------------------------------------------------------------- 1 | using ExpressBase.Common; 2 | using ExpressBase.Common.Constants; 3 | using ExpressBase.Common.Data; 4 | using ExpressBase.Common.ServiceStack; 5 | using ExpressBase.Common.ServiceStack.Auth; 6 | using ExpressBase.Objects.ServiceStack_Artifacts; 7 | using ExpressBase.Security; 8 | using ServiceStack; 9 | using ServiceStack.Auth; 10 | using ServiceStack.Configuration; 11 | using ServiceStack.Logging; 12 | using ServiceStack.Redis; 13 | using System; 14 | 15 | namespace ExpressBase.ServiceStack.Auth0 16 | { 17 | public class MyCredentialsAuthProvider : CredentialsAuthProvider 18 | { 19 | private RedisClient Redis { get; set; } 20 | 21 | public MyCredentialsAuthProvider(IAppSettings settings) : base(settings) { } 22 | 23 | private ILog Logger 24 | { 25 | get { return LogManager.GetLogger(GetType()); } 26 | } 27 | 28 | public override bool TryAuthenticate(IServiceBase authService, string UserName, string password) 29 | { 30 | try 31 | { 32 | Logger.Info("In TryAuthenticate method1"); 33 | 34 | var request = authService.Request.Dto as Authenticate; 35 | var cid = request.Meta.ContainsKey(TokenConstants.CID) ? request.Meta[TokenConstants.CID] : string.Empty; 36 | var socialId = request.Meta.ContainsKey(TokenConstants.SOCIALID) ? request.Meta[TokenConstants.SOCIALID] : string.Empty; 37 | var whichContext = request.Meta[TokenConstants.WC].ToLower().Trim(); 38 | string ip = request.Meta.ContainsKey(TokenConstants.IP) ? request.Meta[TokenConstants.IP] : string.Empty; 39 | string userAgent = request.Meta.ContainsKey("useragent") ? request.Meta["useragent"] : string.Empty; 40 | string deviceId = request.Meta.ContainsKey("deviceid") ? request.Meta["deviceid"] : string.Empty; 41 | 42 | var EbConnectionFactory = authService.TryResolve() as EbConnectionFactory; 43 | 44 | Logger.Info("In TryAuthenticate method2"); 45 | //string[] app_types = { "Mobile", "Web", "Bot" }; 46 | //if (request.Meta["context"] == "tc" || request.Meta["context"] == "dc") 47 | // app_types 48 | 49 | //if (request.Meta.ContainsKey("signup_tok")) 50 | // { 51 | // cid = CoreConstants.EXPRESSBASE; 52 | // _authUser = User.GetInfraVerifiedUser(EbConnectionFactory.DataDB, UserName, request.Meta["signup_tok"]); 53 | // } 54 | 55 | User _authUser = null; 56 | if (whichContext.Equals(RoutingConstants.TC)) 57 | { 58 | _authUser = User.GetDetailsTenant(EbConnectionFactory.DataDB, UserName, password, ip); 59 | Logger.Info("TryAuthenticate -> Tenant"); 60 | } 61 | else if (request.Meta.ContainsKey("anonymous"))// && whichContext.Equals("bc")) 62 | { 63 | var emailId = request.Meta.ContainsKey("emailId") ? request.Meta["emailId"] : string.Empty;//for anonymous 64 | var phone = request.Meta.ContainsKey("phone") ? request.Meta["phone"] : string.Empty;//for anonymous 65 | var appid = request.Meta.ContainsKey("appid") ? Convert.ToInt32(request.Meta["appid"]) : 0;//for anonymous 66 | var user_ip = request.Meta.ContainsKey("user_ip") ? request.Meta["user_ip"] : string.Empty;//for anonymous 67 | var user_name = request.Meta.ContainsKey("user_name") ? request.Meta["user_name"] : string.Empty;//for anonymous 68 | var user_browser = request.Meta.ContainsKey("user_browser") ? request.Meta["user_browser"] : string.Empty;//for anonymous 69 | var city = request.Meta.ContainsKey("city") ? request.Meta["city"] : string.Empty;//for anonymous 70 | var region = request.Meta.ContainsKey("region") ? request.Meta["region"] : string.Empty;//for anonymous 71 | var country = request.Meta.ContainsKey("country") ? request.Meta["country"] : string.Empty;//for anonymous 72 | var latitude = request.Meta.ContainsKey("latitude") ? request.Meta["latitude"] : string.Empty;//for anonymous 73 | var longitude = request.Meta.ContainsKey("longitude") ? request.Meta["longitude"] : string.Empty;//for anonymous 74 | var timezone = request.Meta.ContainsKey("timezone") ? request.Meta["timezone"] : string.Empty;//for anonymous 75 | var iplocationjson = request.Meta.ContainsKey("iplocationjson") ? request.Meta["iplocationjson"] : string.Empty;//for anonymous 76 | 77 | _authUser = User.GetDetailsAnonymous(EbConnectionFactory.DataDB, socialId, emailId, phone, appid, whichContext, user_ip, user_name, user_browser, city, region, country, latitude, longitude, timezone, iplocationjson); 78 | 79 | Logger.Info("TryAuthenticate -> anonymous"); 80 | 81 | } 82 | else if (!string.IsNullOrEmpty(socialId)) 83 | { 84 | 85 | _authUser = User.GetDetailsSocial(EbConnectionFactory.DataDB, socialId, whichContext, ip, deviceId, userAgent); 86 | Logger.Info("TryAuthenticate -> socialId"); 87 | 88 | } 89 | else if (request.Meta.ContainsKey("sso") && (whichContext.Equals("dc") || whichContext.Equals("uc"))) 90 | { 91 | 92 | _authUser = User.GetDetailsSSO(EbConnectionFactory.DataDB, UserName, whichContext, ip, deviceId, userAgent); 93 | Logger.Info("TryAuthenticate -> sso"); 94 | 95 | } 96 | else 97 | { 98 | _authUser = User.GetDetailsNormal(EbConnectionFactory.DataDB, UserName, password, whichContext, ip, deviceId, userAgent); 99 | Logger.Info("TryAuthenticate -> Normal"); 100 | 101 | } 102 | if (_authUser != null) 103 | { 104 | if (_authUser.UserId == -1) 105 | throw new Exception("Access Denied"); 106 | if (_authUser.Email != null) 107 | { 108 | CustomUserSession session = authService.GetSession(false) as CustomUserSession; 109 | var redisClient = authService.TryResolve().GetClient(); 110 | if (_authUser.Email.Equals(TokenConstants.ANONYM_EMAIL)) 111 | { 112 | session.Aid = _authUser.UserId; 113 | _authUser.UserId = 1; 114 | } 115 | session.CId = cid; 116 | _authUser.CId = cid; 117 | session.Uid = _authUser.UserId; 118 | session.Email = _authUser.Email; 119 | session.IsAuthenticated = true; 120 | session.User = _authUser; 121 | session.WhichConsole = whichContext; 122 | session.DBVendor = EbConnectionFactory.DataDB.Vendor; 123 | _authUser.wc = whichContext; 124 | _authUser.AuthId = string.Format(TokenConstants.SUB_FORMAT, cid, _authUser.UserId, whichContext); 125 | session.UserAuthId = _authUser.AuthId; 126 | session.SourceIp = _authUser.SourceIp; 127 | 128 | var authRepo = HostContext.AppHost.GetAuthRepository(authService.Request); 129 | var existingUser = (authRepo as MyRedisAuthRepository).GetUserAuth(session.UserAuthId); 130 | (authRepo as MyRedisAuthRepository).UpdateUserAuth(existingUser, _authUser); 131 | } 132 | } 133 | return (_authUser != null); 134 | 135 | } catch(Exception ee) 136 | { 137 | if (ee.Message == "Access Denied") 138 | throw new Exception("Access Denied"); 139 | Logger.Info("Exception: "+ ee.ToJson()); 140 | throw ee; 141 | } 142 | } 143 | 144 | public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request) 145 | { 146 | Logger.Info("Authenticate -> Start"); 147 | AuthenticateResponse authResponse; 148 | try 149 | { 150 | authResponse = base.Authenticate(authService, session, request) as AuthenticateResponse; 151 | if (authResponse.UserId != null) 152 | { 153 | var _customUserSession = authService.GetSession() as CustomUserSession; 154 | _customUserSession.WhichConsole = request.Meta.ContainsKey(RoutingConstants.WC) ? request.Meta[RoutingConstants.WC] : string.Empty; 155 | 156 | if (!string.IsNullOrEmpty(authResponse.SessionId) && _customUserSession != null) 157 | { 158 | Logger.Info("In Authenticate method3"); 159 | return new MyAuthenticateResponse 160 | { 161 | UserId = _customUserSession.UserAuthId, 162 | UserName = _customUserSession.UserName, 163 | User = _customUserSession.User, 164 | SessionId = _customUserSession.Id, 165 | AnonId = _customUserSession.Aid 166 | }; 167 | } 168 | return authResponse; 169 | } 170 | else 171 | { 172 | throw new Exception("er_server"); 173 | } 174 | } 175 | catch (Exception e) 176 | { 177 | if (e.Message == "Invalid UserName or Password") 178 | throw new Exception("Invalid Username or Password"); 179 | else if (e.Message == "Access Denied") 180 | throw new Exception("Access Denied"); 181 | else 182 | throw new Exception("Internal Server Error"); 183 | } 184 | } 185 | 186 | public override object Logout(IServiceBase service, Authenticate request) 187 | { 188 | try 189 | { 190 | CustomUserSession session = service.GetSession() as CustomUserSession; 191 | User User = (service as AuthenticateService).Redis.Get(session.UserAuthId); 192 | EbConnectionFactory EbConnectionFactory = service.TryResolve() as EbConnectionFactory; 193 | User.Logout(EbConnectionFactory.DataDB); 194 | } 195 | catch(Exception ex) 196 | { 197 | Console.WriteLine("Exception in Logout : " + ex.Message); 198 | } 199 | return base.Logout(service, request); 200 | } 201 | } 202 | } 203 | -------------------------------------------------------------------------------- /Auth0/MyGoogleAuthProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace ExpressBase.ServiceStack.Auth0 7 | { 8 | public class MyGoogleAuthProvider 9 | { 10 | 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Auth0/MyLinkedInAuthProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace ExpressBase.ServiceStack.Auth0 7 | { 8 | public class MyLinkedInAuthProvider 9 | { 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Auth0/MyTwitterAuthProvider.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using ExpressBase.Data; 3 | using ExpressBase.Objects.ServiceStack_Artifacts; 4 | using ServiceStack; 5 | using ServiceStack.Auth; 6 | using ServiceStack.Configuration; 7 | using ServiceStack.Web; 8 | using ExpressBase.Common; 9 | using ExpressBase.Common.Data; 10 | using ExpressBase.Common.Constants; 11 | using ExpressBase.Common.Structures; 12 | using ExpressBase.Common.ServiceStack.Auth; 13 | using Newtonsoft.Json; 14 | using System; 15 | using System.Data.Common; 16 | using System.Threading.Tasks; 17 | using ExpressBase.Common.Extensions; 18 | 19 | namespace ExpressBase.ServiceStack 20 | { 21 | public class MyTwitterAuthProvider : TwitterAuthProvider 22 | { 23 | 24 | public MyTwitterAuthProvider(IAppSettings settings) : base(settings) { } 25 | 26 | public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request) 27 | { 28 | var objret = base.Authenticate(authService, session, request); 29 | 30 | // no need if email present change to email 31 | 32 | if (!string.IsNullOrEmpty(session.ProviderOAuthAccess[0].DisplayName)) 33 | { 34 | EbConnectionFactory InfraConnectionFactory = authService.ResolveService() as EbConnectionFactory; 35 | 36 | if (!string.IsNullOrEmpty(session.ProviderOAuthAccess[0].Email)) 37 | { 38 | string b = string.Empty; 39 | try 40 | { 41 | bool unique = false; 42 | string sql1 = "SELECT id, pwd FROM eb_tenants WHERE email ~* @email"; 43 | DbParameter[] parameters2 = { InfraConnectionFactory.DataDB.GetNewParameter("email", EbDbTypes.String, session.ProviderOAuthAccess[0].Email) }; 44 | EbDataTable dt = InfraConnectionFactory.DataDB.DoQuery(sql1, parameters2); 45 | if (dt.Rows.Count > 0) 46 | { 47 | unique = false; 48 | } 49 | else 50 | unique = true; 51 | //string sql11 = "SELECT id, pwd FROM eb_tenants WHERE email ~* @email"; 52 | //DbParameter[] parameters22 = { InfraConnectionFactory.DataDB.GetNewParameter("email", EbDbTypes.String, session.ProviderOAuthAccess[0].Email) }; 53 | //int dtq = InfraConnectionFactory.DataDB.DoNonQuery(sql11, parameters22); 54 | if (unique == true) 55 | { 56 | DbParameter[] parameter1 = { 57 | InfraConnectionFactory.DataDB.GetNewParameter("email", EbDbTypes.String, session.ProviderOAuthAccess[0].Email), 58 | InfraConnectionFactory.DataDB.GetNewParameter("name", EbDbTypes.String, session.ProviderOAuthAccess[0].UserName), 59 | InfraConnectionFactory.DataDB.GetNewParameter("twitterid", EbDbTypes.String, (session.ProviderOAuthAccess[0].UserId).ToString()), 60 | InfraConnectionFactory.DataDB.GetNewParameter("password", EbDbTypes.String, (session.ProviderOAuthAccess[0].UserId.ToString()+session.ProviderOAuthAccess[0].Email.ToString()).ToMD5Hash()), 61 | 62 | }; 63 | 64 | EbDataTable dtbl = InfraConnectionFactory.DataDB.DoQuery(@"INSERT INTO eb_tenants (email,fullname,twitter_id,pwd) 65 | VALUES 66 | (:email,:name,:twitterid,:password) RETURNING id;", parameter1); 67 | 68 | 69 | } 70 | SocialSignup sco_signup = new SocialSignup 71 | { 72 | AuthProvider = session.ProviderOAuthAccess[0].Provider, 73 | Country = session.ProviderOAuthAccess[0].Country, 74 | Email = session.ProviderOAuthAccess[0].Email, 75 | Social_id = (session.ProviderOAuthAccess[0].UserId).ToString(), 76 | Fullname = session.ProviderOAuthAccess[0].UserName, 77 | //IsVerified = session.IsAuthenticated, 78 | Pauto = (session.ProviderOAuthAccess[0].UserId.ToString() + session.ProviderOAuthAccess[0].Email.ToString()).ToMD5Hash(), 79 | UniqueEmail = unique, 80 | }; 81 | b = JsonConvert.SerializeObject(sco_signup); 82 | return authService.Redirect(SuccessRedirectUrlFilter(this, string.Format("http://localhost:41500/social_oauth?scosignup={0}", b))); 83 | 84 | } 85 | catch (Exception e) 86 | { 87 | Console.WriteLine("Exception: " + e.Message + e.StackTrace); 88 | } 89 | } 90 | //using (var con = _InfraDb.DataDB.GetNewConnection()) 91 | //{ 92 | // con.Open(); 93 | // var cmd = _InfraDb.DataDB.GetNewCommand(con, "INSERT INTO eb_users (email,firstname,socialid,prolink) VALUES(@email, @firstname,@socialid,@prolink) ON CONFLICT(socialid) DO UPDATE SET loginattempts = eb_users.loginattempts + EXCLUDED.loginattempts RETURNING eb_users.loginattempts"); 94 | // cmd.Parameters.Add(_InfraDb.DataDB.GetNewParameter("email", EbDbTypes.String, session.ProviderOAuthAccess[0].Email)); 95 | // cmd.Parameters.Add(_InfraDb.DataDB.GetNewParameter("firstname", EbDbTypes.String, session.ProviderOAuthAccess[0].DisplayName)); 96 | // cmd.Parameters.Add(_InfraDb.DataDB.GetNewParameter("socialid", EbDbTypes.String, session.ProviderOAuthAccess[0].UserName)); 97 | // cmd.Parameters.Add(_InfraDb.DataDB.GetNewParameter("prolink", EbDbTypes.String, session.ProviderOAuthAccess[0].Items["profileUrl"])); 98 | // cmd.ExecuteNonQuery(); 99 | //} 100 | 101 | //(session as CustomUserSession).Company = CoreConstants.EXPRESSBASE; 102 | //(session as CustomUserSession).WhichConsole = "tc"; 103 | //return authService.Redirect(SuccessRedirectUrlFilter(this, "http://localhost:5000/Ext/AfterSignInSocial?email=" + session.Email + "&socialId=" + session.UserName + "&provider=" + session.AuthProvider + "&providerToken=" + session.ProviderOAuthAccess[0].AccessTokenSecret)); 104 | } 105 | 106 | return objret; 107 | } 108 | 109 | public override string CreateOrMergeAuthSession(IAuthSession session, IAuthTokens tokens) 110 | { 111 | return base.CreateOrMergeAuthSession(session, tokens); 112 | } 113 | 114 | public override bool Equals(object obj) 115 | { 116 | return base.Equals(obj); 117 | } 118 | 119 | public override int GetHashCode() 120 | { 121 | return base.GetHashCode(); 122 | } 123 | 124 | public override bool IsAccountLocked(IAuthRepository authRepo, IUserAuth userAuth, IAuthTokens tokens = null) 125 | { 126 | return base.IsAccountLocked(authRepo, userAuth, tokens); 127 | } 128 | 129 | public override bool IsAuthorized(IAuthSession session, IAuthTokens tokens, Authenticate request = null) 130 | { 131 | return base.IsAuthorized(session, tokens, request); 132 | } 133 | 134 | public override void LoadUserOAuthProvider(IAuthSession authSession, IAuthTokens tokens) 135 | { 136 | base.LoadUserOAuthProvider(authSession, tokens); 137 | } 138 | 139 | public override object Logout(IServiceBase service, Authenticate request) 140 | { 141 | return base.Logout(service, request); 142 | } 143 | 144 | 145 | 146 | 147 | 148 | //************is this for authanticate******** 149 | 150 | 151 | public override IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary authInfo) 152 | { 153 | return base.OnAuthenticated(authService, session, tokens, authInfo); 154 | } 155 | 156 | public override void OnFailedAuthentication(IAuthSession session, IRequest httpReq, IResponse httpRes) 157 | { 158 | base.OnFailedAuthentication(session, httpReq, httpRes); 159 | } 160 | 161 | public override Task OnFailedAuthenticationAsync(IAuthSession session, IRequest httpReq, IResponse httpRes) 162 | { 163 | return base.OnFailedAuthenticationAsync(session, httpReq, httpRes); 164 | } 165 | 166 | public override string ToString() 167 | { 168 | return base.ToString(); 169 | } 170 | 171 | protected override object ConvertToClientError(object failedResult, bool isHtml) 172 | { 173 | return base.ConvertToClientError(failedResult, isHtml); 174 | } 175 | 176 | protected override bool EmailAlreadyExists(IAuthRepository authRepo, IUserAuth userAuth, IAuthTokens tokens = null) 177 | { 178 | return base.EmailAlreadyExists(authRepo, userAuth, tokens); 179 | } 180 | 181 | protected override string GetAuthRedirectUrl(IServiceBase authService, IAuthSession session) 182 | { 183 | return base.GetAuthRedirectUrl(authService, session); 184 | } 185 | 186 | protected override IAuthRepository GetAuthRepository(IRequest req) 187 | { 188 | return base.GetAuthRepository(req); 189 | } 190 | 191 | protected override string GetReferrerUrl(IServiceBase authService, IAuthSession session, Authenticate request = null) 192 | { 193 | return base.GetReferrerUrl(authService, session, request); 194 | } 195 | 196 | protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary authInfo) 197 | { 198 | base.LoadUserAuthInfo(userSession, tokens, authInfo); 199 | } 200 | 201 | protected override bool UserNameAlreadyExists(IAuthRepository authRepo, IUserAuth userAuth, IAuthTokens tokens = null) 202 | { 203 | return base.UserNameAlreadyExists(authRepo, userAuth, tokens); 204 | } 205 | 206 | protected override IHttpResult ValidateAccount(IServiceBase authService, IAuthRepository authRepo, IAuthSession session, IAuthTokens tokens) 207 | { 208 | return base.ValidateAccount(authService, authRepo, session, tokens); 209 | } 210 | } 211 | } -------------------------------------------------------------------------------- /ExpressBase.ServiceStack.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netcoreapp2.1 5 | 0a068b3f-c82c-4550-9716-d2e112ec69b0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | Always 18 | 19 | 20 | Always 21 | 22 | 23 | Always 24 | 25 | 26 | Always 27 | 28 | 29 | PreserveNewest 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | false 40 | false 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 57 | 58 | 59 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /MQServices/ApiService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using ExpressBase.Common.Data; 4 | using ExpressBase.Common.Helpers; 5 | using ExpressBase.Common.ServiceClients; 6 | using ExpressBase.CoreBase.Globals; 7 | using ExpressBase.Objects; 8 | using ExpressBase.Objects.Services; 9 | using ExpressBase.Objects.ServiceStack_Artifacts; 10 | using Newtonsoft.Json.Linq; 11 | using ServiceStack; 12 | using ServiceStack.Messaging; 13 | 14 | namespace ExpressBase.ServiceStack.MQServices 15 | { 16 | [Restrict(InternalOnly = true)] 17 | public class ApiInternalService : EbMqBaseService 18 | { 19 | private EbApi Api { set; get; } 20 | 21 | public ApiInternalService( IMessageProducer _mqp) : base( _mqp) 22 | { 23 | 24 | } 25 | 26 | public Dictionary ProcessGlobalDictionary(Dictionary data) 27 | { 28 | Dictionary globalParams = new Dictionary(); 29 | if (!(data is null)) 30 | { 31 | foreach (KeyValuePair kp in data) 32 | { 33 | if (kp.Value == null) continue; 34 | 35 | if (kp.Value is string parsed) 36 | { 37 | parsed = parsed.Trim(); 38 | 39 | if ((parsed.StartsWith("{") && parsed.EndsWith("}")) || (parsed.StartsWith("[") && parsed.EndsWith("]"))) 40 | { 41 | string formated = parsed.Replace(@"\", string.Empty); 42 | globalParams.Add(kp.Key, JObject.Parse(formated)); 43 | } 44 | else 45 | globalParams.Add(kp.Key, kp.Value); 46 | } 47 | else 48 | { 49 | globalParams.Add(kp.Key, kp.Value); 50 | } 51 | } 52 | } 53 | return globalParams; 54 | } 55 | 56 | public ApiResponse Any(ApiMqRequest request) 57 | { 58 | try 59 | { 60 | GetApiObject(request); 61 | InitializeExecution(); 62 | } 63 | catch (Exception e) 64 | { 65 | Console.WriteLine("---API SERVICE END POINT EX CATCH---"); 66 | Console.WriteLine(e.Message + "\n" + e.StackTrace); 67 | } 68 | return this.Api.ApiResponse; 69 | } 70 | 71 | public void GetApiObject(ApiMqRequest request) 72 | { 73 | int UserId; 74 | string SolutionId; 75 | string UserAuthId; 76 | Dictionary ApiData; 77 | 78 | if ((request.HasRefId() || request.HasObjectId()) && request.JobArgs != null) 79 | { 80 | SolutionId = request.JobArgs.SolnId; 81 | UserAuthId = request.JobArgs.UserAuthId; 82 | ApiData = request.JobArgs.ApiData; 83 | UserId = request.JobArgs.UserId; 84 | 85 | try 86 | { 87 | this.Api = new EbApi(); 88 | this.EbConnectionFactory = new EbConnectionFactory(SolutionId, Redis); 89 | this.Api = Api.GetApi(request.JobArgs.RefId, request.JobArgs.ObjId, this.Redis, this.EbConnectionFactory.DataDB, this.EbConnectionFactory.ObjectsDB); 90 | 91 | } 92 | catch (Exception ex) 93 | { 94 | Console.WriteLine($"Failed resolve api object from refid '{request.JobArgs?.RefId}'"); 95 | Console.WriteLine(ex.Message); 96 | } 97 | } 98 | else 99 | { 100 | SolutionId = request.SolnId; 101 | UserAuthId = request.UserAuthId; 102 | ApiData = request.Data; 103 | UserId = request.UserId; 104 | 105 | try 106 | { 107 | this.EbConnectionFactory = new EbConnectionFactory(SolutionId, Redis); 108 | this.Api = EbApiHelper.GetApiByName(request.Name, request.Version, this.EbConnectionFactory.ObjectsDB); 109 | if (!(this.Api is null)) 110 | { 111 | Api.Redis = this.Redis; 112 | Api.ObjectsDB = this.EbConnectionFactory.ObjectsDB; 113 | Api.DataDB = this.EbConnectionFactory.DataDB; 114 | this.Api.ApiResponse = new ApiResponse(); 115 | } 116 | } 117 | catch (Exception ex) 118 | { 119 | Console.WriteLine($"Failed resolve api object from refid '{this.Api?.RefId}'"); 120 | Console.WriteLine(ex.Message); 121 | } 122 | } 123 | 124 | if (this.Api is null) 125 | { 126 | this.Api = new EbApi { ApiResponse = new ApiResponse() }; 127 | this.Api.ApiResponse.Message.ErrorCode = ApiErrorCode.ApiNotFound; 128 | this.Api.ApiResponse.Message.Status = "Api does not exist"; 129 | this.Api.ApiResponse.Message.Description = $"Api does not exist!,"; 130 | 131 | throw new Exception(this.Api.ApiResponse.Message.Description); 132 | } 133 | 134 | this.Api.SolutionId = SolutionId; 135 | this.Api.UserObject = GetUserObject(UserAuthId); 136 | 137 | this.Api.GlobalParams = ProcessGlobalDictionary(ApiData); 138 | this.Api.GlobalParams["eb_currentuser_id"] = UserId; 139 | 140 | if (!this.Api.GlobalParams.ContainsKey("eb_loc_id")) 141 | { 142 | this.Api.GlobalParams["eb_loc_id"] = this.Api.UserObject.Preference.DefaultLocation; 143 | } 144 | } 145 | 146 | private void InitializeExecution() 147 | { 148 | try 149 | { 150 | int r_count = this.Api.Resources.Count; 151 | 152 | while (Api.Step < r_count) 153 | { 154 | this.Api.Resources[Api.Step].Result = this.GetResult(this.Api.Resources[Api.Step]); 155 | Api.Step++; 156 | } 157 | 158 | if (this.Api.ApiResponse.Result == null) 159 | this.Api.ApiResponse.Result = this.Api.Resources[Api.Step - 1].GetResult(); 160 | 161 | this.Api.ApiResponse.Message.Status = "Success"; 162 | this.Api.ApiResponse.Message.ErrorCode = this.Api.ApiResponse.Result == null ? ApiErrorCode.SuccessWithNoReturn : ApiErrorCode.Success; 163 | this.Api.ApiResponse.Message.Description = $"Api execution completed, " + this.Api.ApiResponse.Message.Description; 164 | } 165 | catch (Exception ex) 166 | { 167 | Console.WriteLine("---EXCEPTION AT API-SERVICE [InitializeExecution]---"); 168 | Console.WriteLine(ex.Message); 169 | } 170 | } 171 | 172 | private object GetResult(ApiResources resource) 173 | { 174 | try 175 | { 176 | return EbApiHelper.GetResult(resource, this.Api, MessageProducer3, this, this.FileClient); 177 | } 178 | catch (Exception ex) 179 | { 180 | if (ex is ExplicitExitException) 181 | { 182 | this.Api.ApiResponse.Message.Status = "Success"; 183 | this.Api.ApiResponse.Message.Description = ex.Message; 184 | this.Api.ApiResponse.Message.ErrorCode = ApiErrorCode.ExplicitExit; 185 | } 186 | else 187 | { 188 | this.Api.ApiResponse.Message.Status = "Error"; 189 | this.Api.ApiResponse.Message.Description = $"Failed to execute Resource '{resource.Name}' " + ex.Message; 190 | } 191 | 192 | throw new ApiException("[GetResult] ," + ex.Message); 193 | } 194 | } 195 | } 196 | } 197 | -------------------------------------------------------------------------------- /MQServices/EmailService.cs: -------------------------------------------------------------------------------- 1 | using MailKit.Net.Smtp; 2 | using MimeKit; 3 | using ServiceStack; 4 | using ExpressBase.Objects.ServiceStack_Artifacts; 5 | using System; 6 | using System.Threading.Tasks; 7 | using ServiceStack.Messaging; 8 | using ExpressBase.Objects; 9 | using ExpressBase.Common; 10 | using ExpressBase.Common.Data; 11 | using System.Text; 12 | using System.Collections.Generic; 13 | using System.Text.RegularExpressions; 14 | using System.Data.Common; 15 | using ExpressBase.Common.Constants; 16 | using ExpressBase.Common.Structures; 17 | using ExpressBase.Common.ServiceClients; 18 | using System.Net.Mail; 19 | using System.Net; 20 | using ExpressBase.Objects.Services; 21 | using System.IO; 22 | 23 | namespace ExpressBase.ServiceStack 24 | { 25 | 26 | public class EmailService : EbBaseService 27 | { 28 | public EmailService(IEbConnectionFactory _dbf, IMessageProducer _mqp, IMessageQueueClient _mqc, IEbServerEventClient _sec) : base(_dbf, _mqp, _mqc, _sec) { } 29 | 30 | public EmailServicesResponse Post(EmailDirectRequest request) 31 | { 32 | EmailServicesResponse resp = new EmailServicesResponse(); 33 | try 34 | { 35 | MessageProducer3.Publish(new EmailServicesRequest() 36 | { 37 | To = request.To, 38 | Message = request.Message, 39 | Subject = request.Subject, 40 | UserId = request.UserId, 41 | UserAuthId = request.UserAuthId, 42 | SolnId = request.SolnId, 43 | WhichConsole = request.WhichConsole, 44 | }); 45 | resp.Success = true; 46 | } 47 | catch (Exception e) 48 | { 49 | Console.WriteLine(e.Message + e.StackTrace); 50 | resp.Success = false; 51 | } 52 | return resp; 53 | } 54 | 55 | 56 | //public ResetPasswordMqResponse Post(ResetPasswordMqRequest request) 57 | //{ 58 | // string q = "SELECT * FROM eb_reset_pw(:email)"; 59 | // DbParameter[] parameters = { 60 | // this.EbConnectionFactory.DataDB.GetNewParameter("email",EbDbTypes.String,request.Email) 61 | // }; 62 | // EbDataTable dt = this.EbConnectionFactory.DataDB.DoQuery(q, parameters); 63 | 64 | // MessageProducer3.Publish(new EmailServicesRequest() 65 | // { 66 | // To = request.Email, 67 | // Cc = null, 68 | // Bcc = null, 69 | // Message = "Your new password is" + dt.Rows[0][0], 70 | // Subject = "Reset Password", 71 | // //UserId = request.UserId, 72 | // //UserAuthId = request.UserAuthId, 73 | // SolnId = CoreConstants.EXPRESSBASE, 74 | // //AttachmentReport = RepRes.ReportBytea, 75 | // //AttachmentName = RepRes.ReportName 76 | // }); 77 | // return new ResetPasswordMqResponse { }; 78 | //} 79 | } 80 | 81 | //[Restrict(InternalOnly = true)] 82 | //public class EmailInternalService : EbMqBaseService 83 | //{ 84 | // public EmailInternalService() : base() { } 85 | 86 | // public string Post(EmailServicesRequest request) 87 | // { 88 | // try 89 | // { 90 | // if (request.SolnId == CoreConstants.EXPRESSBASE) 91 | // { 92 | // Console.WriteLine("Inside EmailService/EmailServiceInternal in SS \n Before Email \n To: " + request.To + "\nEmail Connections - infra: " + InfraConnectionFactory.EmailConnection.Capacity); 93 | // this.InfraConnectionFactory.EmailConnection.Send(request.To, request.Subject, request.Message, request.Cc, request.Bcc, request.AttachmentReport, request.AttachmentName, request.ReplyTo); 94 | // } 95 | // else 96 | // { 97 | // base.EbConnectionFactory = new EbConnectionFactory(request.SolnId, this.Redis); 98 | // if (this.EbConnectionFactory.EmailConnection != null) 99 | // { 100 | // Console.WriteLine("Inside EmailService/EmailServiceInternal in SS \n Before Email \n To: " + request.To + "\nEmail Connections - solution: " + EbConnectionFactory.EmailConnection?.Capacity); 101 | // this.EbConnectionFactory.EmailConnection?.Send(request.To, request.Subject, request.Message, request.Cc, request.Bcc, request.AttachmentReport, request.AttachmentName, request.ReplyTo); 102 | // Console.WriteLine("Inside EmailService/EmailServiceInternal in SS \n After Email \nSend To:" + request.To); 103 | // } 104 | // else 105 | // { 106 | // Console.WriteLine("Email Connection not set for " + request.SolnId); 107 | // } 108 | // } 109 | 110 | // } 111 | // catch (Exception e) 112 | // { 113 | // return e.Message; 114 | // } 115 | // return null; 116 | // } 117 | //} 118 | } 119 | -------------------------------------------------------------------------------- /MQServices/ExportToExcelService.cs: -------------------------------------------------------------------------------- 1 | using ExpressBase.Common; 2 | using ExpressBase.Common.Constants; 3 | using ExpressBase.Common.Data; 4 | using ExpressBase.Common.ServerEvents_Artifacts; 5 | using ExpressBase.Common.ServiceClients; 6 | using ExpressBase.Objects.Helpers; 7 | using ExpressBase.Objects.Services; 8 | using ExpressBase.Objects.ServiceStack_Artifacts; 9 | using ServiceStack; 10 | using ServiceStack.Messaging; 11 | using System; 12 | using System.Collections.Generic; 13 | using System.IO; 14 | using System.IO.Compression; 15 | using System.Linq; 16 | using System.Threading.Tasks; 17 | 18 | namespace ExpressBase.ServiceStack.MQServices 19 | { 20 | public class ExportToExcelService : EbBaseService 21 | { 22 | public ExportToExcelService(IMessageProducer _mqp, IMessageQueueClient _mqc) : base(_mqp, _mqc) { } 23 | 24 | [Authenticate] 25 | public void Post(ExportToExcelMqRequest request) 26 | { 27 | try 28 | { 29 | MessageProducer3.Publish(new ExportToExcelServiceRequest() 30 | { 31 | EbDataVisualization = request.EbDataVisualization, 32 | Ispaging = request.Ispaging, 33 | UserInfo = request.UserInfo, 34 | RefId = request.RefId, 35 | IsExcel = request.IsExcel, 36 | Params = request.Params, 37 | TFilters = request.TFilters, 38 | UserId = request.UserId, 39 | UserAuthId = request.UserAuthId, 40 | SolnId = request.SolnId, 41 | eb_solution = request.eb_Solution, 42 | BToken = (!String.IsNullOrEmpty(this.Request.Authorization)) ? this.Request.Authorization.Replace("Bearer", string.Empty).Trim() : String.Empty, 43 | RToken = (!String.IsNullOrEmpty(this.Request.Headers["rToken"])) ? this.Request.Headers["rToken"] : String.Empty, 44 | SubscriptionId = request.SubscriptionId 45 | }); 46 | Console.WriteLine("ExportToExcelServiceRequest pushed to MQ - " + request.RefId); 47 | } 48 | catch (Exception e) 49 | { 50 | Console.WriteLine("Exception in ExportToExcelMqRequest: " + e.Message + e.StackTrace); 51 | } 52 | } 53 | } 54 | 55 | [Restrict(InternalOnly = true)] 56 | public class ExportToExcelInternalService : EbMqBaseService 57 | { 58 | public ExportToExcelInternalService(IMessageProducer _mqp, IMessageQueueClient _mqc, IEbServerEventClient _sec) : base(_mqp, _mqc, _sec) { } 59 | 60 | public void Post(ExportToExcelServiceRequest request) 61 | { 62 | try 63 | { 64 | DataVisService dataservice = base.ResolveService(); 65 | dataservice.EbConnectionFactory = new EbConnectionFactory(request.SolnId, this.Redis); ; 66 | 67 | int id = new DownloadsPageHelper().InsertDownloadFileEntry(dataservice.EbConnectionFactory.DataDB, request.EbDataVisualization.DisplayName + ".xlsx", request.UserId); 68 | 69 | DataSourceDataResponse res = (DataSourceDataResponse)dataservice.Any(new TableDataRequest 70 | { 71 | EbDataVisualization = request.EbDataVisualization, 72 | Ispaging = false, 73 | UserInfo = request.UserInfo, 74 | RefId = request.RefId, 75 | IsExcel = true, 76 | Params = request.Params, 77 | TFilters = request.TFilters, 78 | Token = request.BToken, 79 | rToken = request.RToken, 80 | eb_Solution = request.eb_solution, 81 | UserAuthId = request.UserAuthId 82 | }); 83 | 84 | byte[] compressedData = Compress(res.excel_file); 85 | 86 | // this.Redis.Set("excel" + (request.EbDataVisualization.RefId + request.UserInfo.UserId), compressedData, DateTime.Now.AddMinutes(30)); 87 | new DownloadsPageHelper().SaveDownloadFileBytea(dataservice.EbConnectionFactory.DataDB, compressedData, id); 88 | 89 | this.ServerEventClient.BearerToken = request.BToken; 90 | this.ServerEventClient.RefreshToken = request.RToken; 91 | this.ServerEventClient.RefreshTokenUri = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_GET_ACCESS_TOKEN_URL); 92 | 93 | this.ServerEventClient.Post(new NotifySubscriptionRequest 94 | { 95 | Msg = "/DV/GetExcel?id=" + id, 96 | Selector = StaticFileConstants.EXPORTTOEXCELSUCCESS, 97 | ToSubscriptionId = request.SubscriptionId 98 | }); 99 | } 100 | catch (Exception e) 101 | { 102 | Console.WriteLine("Exception: " + e.Message + e.StackTrace); 103 | } 104 | 105 | } 106 | 107 | public static byte[] Compress(byte[] data) 108 | { 109 | using (MemoryStream memory = new MemoryStream()) 110 | { 111 | using (GZipStream gzip = new GZipStream(memory, 112 | CompressionMode.Compress, true)) 113 | { 114 | gzip.Write(data, 0, data.Length); 115 | } 116 | return memory.ToArray(); 117 | } 118 | } 119 | 120 | } 121 | } -------------------------------------------------------------------------------- /MQServices/PdfToEmailService.cs: -------------------------------------------------------------------------------- 1 | using ExpressBase.Common; 2 | using ExpressBase.Common.Data; 3 | using ExpressBase.Common.ServiceClients; 4 | using ExpressBase.Common.Structures; 5 | using ExpressBase.Objects; 6 | using ExpressBase.Objects.Services; 7 | using ExpressBase.Objects.ServiceStack_Artifacts; 8 | using ExpressBase.Security; 9 | using ExpressBase.ServiceStack.Services; 10 | using ServiceStack; 11 | using ServiceStack.Messaging; 12 | using System; 13 | using System.Collections.Generic; 14 | using System.Data.Common; 15 | using System.Linq; 16 | using System.Text.RegularExpressions; 17 | using System.Threading.Tasks; 18 | 19 | namespace ExpressBase.ServiceStack.MQServices 20 | { 21 | [Authenticate] 22 | public class EmailTemplateSendService : EbBaseService 23 | { 24 | public EmailTemplateSendService(IMessageProducer _mqp, IMessageQueueClient _mqc) : base(_mqp, _mqc) { } 25 | 26 | public void Post(EmailTemplateWithAttachmentMqRequest request) 27 | { 28 | MessageProducer3.Publish(new EmailAttachmentRequest() 29 | { 30 | ObjId = request.ObjId, 31 | Params = request.Params, 32 | UserId = request.UserId, 33 | UserAuthId = request.UserAuthId, 34 | SolnId = request.SolnId, 35 | RefId = request.RefId, 36 | BToken = request.BToken, 37 | RToken = request.RToken 38 | }); 39 | Console.WriteLine("EmailTemplateWithAttachment publish complete"); 40 | } 41 | } 42 | 43 | [Authenticate] 44 | [Restrict(InternalOnly = true)] 45 | public class EmailTemplateSendInternalService : EbMqBaseService 46 | { 47 | public EmailTemplateSendInternalService(IMessageProducer _mqp, IMessageQueueClient _mqc) : base(_mqp, _mqc) { } 48 | 49 | EbEmailTemplate Template = new EbEmailTemplate(); 50 | 51 | EbDataSet DataSet; 52 | 53 | public void Post(EmailAttachmentRequest request) 54 | { 55 | Console.WriteLine("EmailTemplateWithAttachment mq internal started"); 56 | 57 | EbConnectionFactory ebConnectionFactory = new EbConnectionFactory(request.SolnId, this.Redis); 58 | EbObjectService objservice = base.ResolveService(); 59 | ReportService reportservice = base.ResolveService(); 60 | reportservice.EbConnectionFactory = objservice.EbConnectionFactory = ebConnectionFactory; 61 | 62 | if (request.ObjId > 0) 63 | { 64 | EbObjectFetchLiveVersionResponse template_res = (EbObjectFetchLiveVersionResponse)objservice.Get(new EbObjectFetchLiveVersionRequest() { Id = request.ObjId }); 65 | if (template_res?.Data.Count > 0) 66 | { 67 | this.Template = EbSerializers.Json_Deserialize(template_res.Data[0].Json); 68 | } 69 | } 70 | else if (request.RefId != string.Empty) 71 | { 72 | EbObjectParticularVersionResponse template_res = (EbObjectParticularVersionResponse)objservice.Get(new EbObjectParticularVersionRequest() { RefId = request.RefId }); 73 | if (template_res?.Data.Count > 0) 74 | { 75 | this.Template = EbSerializers.Json_Deserialize(template_res.Data[0].Json); 76 | } 77 | } 78 | 79 | if (this.Template != null) 80 | { 81 | if (this.Template.DataSourceRefId != string.Empty && this.Template.To != string.Empty) 82 | { 83 | EbObjectParticularVersionResponse mailDs = (EbObjectParticularVersionResponse)objservice.Get(new EbObjectParticularVersionRequest() { RefId = this.Template.DataSourceRefId }); 84 | if (mailDs.Data.Count > 0) 85 | { 86 | EbDataReader dr = EbSerializers.Json_Deserialize(mailDs.Data[0].Json); 87 | IEnumerable parameters = DataHelper.GetParams(ebConnectionFactory.ObjectsDB, false, request.Params, 0, 0); 88 | DataSet = ebConnectionFactory.ObjectsDB.DoQueries(dr?.Sql, parameters.ToArray()); 89 | Fill(); 90 | } 91 | } 92 | if (this.Template.To != string.Empty) 93 | { 94 | EmailServicesRequest request1 = new EmailServicesRequest() 95 | { 96 | To = this.Template.To, 97 | Cc = this.Template?.Cc?.Split(","), 98 | Bcc = this.Template?.Bcc?.Split(","), 99 | Message = this.Template?.Body, 100 | Subject = this.Template?.Subject, 101 | UserId = request.UserId, 102 | UserAuthId = request.UserAuthId, 103 | SolnId = request.SolnId, 104 | ReplyTo = this.Template?.ReplyTo, 105 | Params = request.Params, 106 | RefId = this.Template?.RefId 107 | }; 108 | 109 | //adding email attachment. type pdf 110 | if (!string.IsNullOrEmpty(Template.AttachmentReportRefID)) 111 | { 112 | ReportRenderResponse RepRes = reportservice.Get(new ReportRenderRequest 113 | { 114 | Refid = this.Template.AttachmentReportRefID, 115 | Params = request.Params, 116 | SolnId = request.SolnId, 117 | ReadingUserAuthId = request.UserAuthId, 118 | RenderingUserAuthId = request.UserAuthId, 119 | BToken = request.BToken, 120 | RToken = request.RToken 121 | }); 122 | if (RepRes?.StreamWrapper?.Memorystream != null) 123 | { 124 | RepRes.StreamWrapper.Memorystream.Position = 0; 125 | request1.AttachmentReport = RepRes.ReportBytea; 126 | request1.AttachmentName = RepRes.ReportName + ".pdf"; 127 | Console.WriteLine("EmailTemplateWithAttachment.Attachment Added"); 128 | } 129 | } 130 | MessageProducer3.Publish(request1); 131 | Console.WriteLine("Published to Email send"); 132 | } 133 | else 134 | { 135 | Console.WriteLine("Email.To is empty " + this.Template.AttachmentReportRefID); 136 | } 137 | } 138 | else 139 | { 140 | throw new Exception("Template is empty :" + Template.RefId); 141 | } 142 | } 143 | 144 | public void Fill() 145 | { 146 | this.Template.Body = ReplacePlaceholders(this.Template.Body); 147 | this.Template.Subject = ReplacePlaceholders(this.Template.Subject); 148 | this.Template.To = ReplacePlaceholders(this.Template.To); 149 | this.Template.Cc = ReplacePlaceholders(this.Template.Cc); 150 | this.Template.Bcc = ReplacePlaceholders(this.Template.Bcc); 151 | this.Template.ReplyTo = ReplacePlaceholders(this.Template.ReplyTo); 152 | } 153 | 154 | public string ReplacePlaceholders(string text) 155 | { 156 | if (!String.IsNullOrEmpty(text)) 157 | { 158 | string pattern = @"\{{(.*?)\}}"; 159 | IEnumerable matches = Regex.Matches(text, pattern).OfType().Select(m => m.Groups[0].Value).Distinct(); 160 | foreach (string _col in matches) 161 | { 162 | try 163 | { 164 | string str = _col.Replace("{{", "").Replace("}}", ""); 165 | int tbl = Convert.ToInt32(str.Split('.')[0].Replace("Table", "")); 166 | string colval = string.Empty; 167 | if (DataSet.Tables[tbl - 1].Rows.Count > 0) 168 | colval = DataSet.Tables[tbl - 1].Rows[0][str.Split('.')[1]].ToString(); 169 | text = text.Replace(_col, colval); 170 | } 171 | catch (Exception e) 172 | { 173 | throw new Exception("EmailTemplateWithAttachment.matches fill Exception, col:" + _col); 174 | } 175 | } 176 | } 177 | return text; 178 | } 179 | } 180 | } 181 | 182 | -------------------------------------------------------------------------------- /MQServices/RefreshSolutionConnections.cs: -------------------------------------------------------------------------------- 1 | using ExpressBase.Common; 2 | using ExpressBase.Common.Connections; 3 | using ExpressBase.Common.Constants; 4 | using ExpressBase.Common.Data; 5 | using ExpressBase.Objects.Services; 6 | using ExpressBase.Objects.ServiceStack_Artifacts; 7 | using ServiceStack; 8 | using ServiceStack.Messaging; 9 | using System; 10 | using System.Data; 11 | 12 | namespace ExpressBase.ServiceStack.MQServices 13 | { 14 | [Restrict(InternalOnly = true)] 15 | public class RefreshSolutionConnections : EbMqBaseService 16 | { 17 | public RefreshSolutionConnections(IMessageProducer _mqp) : base(_mqp) { } 18 | public UpdateRedisConnectionsMqResponse Post(UpdateRedisConnectionsMqRequest request) 19 | { 20 | string q = @"SELECT esolution_id,isolution_id FROM eb_solutions WHERE eb_del=false;"; 21 | try 22 | { 23 | EbDataTable dt = this.InfraConnectionFactory.DataDB.DoQuery(q); 24 | foreach (EbDataRow row in dt.Rows) 25 | { 26 | 27 | string SolutionId = row["isolution_id"].ToString(); 28 | if (SolutionId != string.Empty) 29 | this.MessageProducer3.Publish(new RefreshSolutionConnectionsRequest { SolnId = SolutionId }); 30 | } 31 | } 32 | catch (Exception e) 33 | { 34 | Console.WriteLine("Exception at update sid map"); 35 | Console.WriteLine(e.Message); 36 | Console.WriteLine(e.StackTrace); 37 | } 38 | 39 | return new UpdateRedisConnectionsMqResponse(); 40 | } 41 | //public bool Post(RefreshSolutionConnectionsRequest req) 42 | //{ 43 | // using (var con = this.InfraConnectionFactory.DataDB.GetNewConnection() as Npgsql.NpgsqlConnection) 44 | // { 45 | // try 46 | // { 47 | // con.Open(); 48 | // string sql = @"SELECT con_type, con_obj FROM eb_connections WHERE solution_id = @solution_id AND eb_del = 'F'"; 49 | // DataTable dt = new DataTable(); 50 | // var ada = new Npgsql.NpgsqlDataAdapter(sql, con); 51 | // ada.SelectCommand.Parameters.Add(new Npgsql.NpgsqlParameter("solution_id", NpgsqlTypes.NpgsqlDbType.Text) { Value = req.TenantAccountId }); 52 | // ada.Fill(dt); 53 | 54 | // EbConnectionsConfig cons = new EbConnectionsConfig(); 55 | // foreach (DataRow dr in dt.Rows) 56 | // { 57 | // if (dr["con_type"].ToString() == EbConnectionTypes.EbDATA.ToString()) 58 | // cons.DataDbConnection = EbSerializers.Json_Deserialize(dr["con_obj"].ToString()); 59 | // else if (dr["con_type"].ToString() == EbConnectionTypes.EbDATA_RO.ToString()) 60 | // cons.DataDbConnection = EbSerializers.Json_Deserialize(dr["con_obj"].ToString()); 61 | // else if (dr["con_type"].ToString() == EbConnectionTypes.EbOBJECTS.ToString()) 62 | // cons.ObjectsDbConnection = EbSerializers.Json_Deserialize(dr["con_obj"].ToString()); 63 | // else if (dr["con_type"].ToString() == EbConnectionTypes.EbFILES.ToString()) 64 | // cons.FilesDbConnection = EbSerializers.Json_Deserialize(dr["con_obj"].ToString()); 65 | // else if (dr["con_type"].ToString() == EbConnectionTypes.EbLOGS.ToString()) 66 | // cons.LogsDbConnection = EbSerializers.Json_Deserialize(dr["con_obj"].ToString()); 67 | // else if (dr["con_type"].ToString() == EbConnectionTypes.SMTP.ToString()) 68 | // cons.SMTPConnection = EbSerializers.Json_Deserialize(dr["con_obj"].ToString()); 69 | // else if (dr["con_type"].ToString() == EbConnectionTypes.SMS.ToString()) 70 | // cons.SMSConnection = EbSerializers.Json_Deserialize(dr["con_obj"].ToString()); 71 | // // ... More to come 72 | // } 73 | 74 | // Redis.Set(string.Format(CoreConstants.SOLUTION_CONNECTION_REDIS_KEY, req.TenantAccountId), cons); 75 | 76 | // return true; 77 | // } 78 | // catch (Exception e) 79 | // { 80 | // Log.Info("Exception:" + e.ToString()); 81 | // return false; 82 | // } 83 | // } 84 | //} 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /MQServices/RefreshSolutionIdMap.cs: -------------------------------------------------------------------------------- 1 | using ExpressBase.Common; 2 | using ExpressBase.Common.Constants; 3 | using ExpressBase.Common.Data; 4 | using ExpressBase.Common.Objects; 5 | using ExpressBase.Common.ServiceClients; 6 | using ExpressBase.Objects; 7 | using ExpressBase.Objects.Services; 8 | using ExpressBase.Objects.ServiceStack_Artifacts; 9 | using ExpressBase.ServiceStack.Services; 10 | using Newtonsoft.Json; 11 | using ServiceStack; 12 | using ServiceStack.Messaging; 13 | using System; 14 | using System.Collections; 15 | using System.Collections.Generic; 16 | using System.Collections.Specialized; 17 | using System.Linq; 18 | using System.Threading.Tasks; 19 | 20 | namespace ExpressBase.ServiceStack.MQServices 21 | { 22 | public class RefreshSolutionIdMap : EbMqBaseService 23 | { 24 | public RefreshSolutionIdMap() : base() { } 25 | 26 | //public UpdateSidMapMqResponse Post(UpdateSidMapMqRequest request) 27 | //{ 28 | 29 | // return new UpdateSidMapMqResponse(); 30 | //} 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /MQServices/ReportService.cs: -------------------------------------------------------------------------------- 1 | using ExpressBase.Common; 2 | using ExpressBase.Common.Constants; 3 | using ExpressBase.Common.Data; 4 | using ExpressBase.Common.Structures; 5 | using ExpressBase.Objects.Services; 6 | using ExpressBase.Objects.ServiceStack_Artifacts; 7 | using ExpressBase.Security; 8 | using ExpressBase.ServiceStack.Services; 9 | using Newtonsoft.Json; 10 | using ServiceStack; 11 | using ServiceStack.Messaging; 12 | using System; 13 | using System.Collections.Generic; 14 | using System.Linq; 15 | using System.Threading.Tasks; 16 | 17 | namespace ExpressBase.ServiceStack.MQServices 18 | { 19 | //[Restrict(InternalOnly = true)] 20 | public class ReportInternalService : EbMqBaseService 21 | { 22 | //public ReportInternalService(IServiceClient _ssclient, IMessageProducer _mqp, IMessageQueueClient _mqc) : base(_ssclient, _mqp, _mqc) 23 | public ReportInternalService(IMessageProducer _mqp, IMessageQueueClient _mqc) : base(_mqp, _mqc) 24 | { 25 | ObjectService = base.ResolveService(); 26 | ReportService = base.ResolveService(); 27 | SchedulersService = base.ResolveService(); 28 | } 29 | 30 | EbObjectService ObjectService { get; set; } 31 | 32 | ReportService ReportService { get; set; } 33 | 34 | SchedulerServices SchedulersService { get; set; } 35 | 36 | ReportRenderResponse RepRes = null; 37 | 38 | EbJobArguments JobArgs = null; 39 | 40 | AllGroupCollection GroupCollection { get; set; } 41 | AllUserCollection UserCollection { get; set; } 42 | 43 | AllDelMessagaeCollection MessageCollection { get; set; } 44 | 45 | Dictionary> Locales = new Dictionary>(); 46 | //Dictionary> SlackLocales = new Dictionary>(); 47 | public ReportInternalResponse Post(ReportInternalRequest request) 48 | { 49 | try 50 | { 51 | Console.WriteLine(" Reached Inside MQService/ReportServiceInternal in SS .. Before Report Render"); 52 | JobArgs = request.JobArgs; 53 | 54 | if (JobArgs != null) 55 | { 56 | EbConnectionFactory ebConnectionFactory = new EbConnectionFactory(JobArgs.SolnId, this.Redis); 57 | ObjectService.EbConnectionFactory = ReportService.EbConnectionFactory = SchedulersService.EbConnectionFactory = ebConnectionFactory; 58 | 59 | 60 | Dictionary LocaleReport = new Dictionary(); 61 | Console.WriteLine(" Fetching Live version " + JobArgs.ObjId); 62 | 63 | EbObjectFetchLiveVersionResponse res = ((EbObjectFetchLiveVersionResponse)ObjectService.Get(new EbObjectFetchLiveVersionRequest() 64 | { 65 | Id = JobArgs.ObjId 66 | })); 67 | 68 | 69 | if (res.Data != null && res.Data.Count > 0 && JobArgs.ToUserIds != null) 70 | { 71 | 72 | UserCollection = JsonConvert.DeserializeObject(JobArgs.ToUserIds); 73 | GroupCollection = JsonConvert.DeserializeObject(JobArgs.ToUserGroupIds); 74 | MessageCollection = JsonConvert.DeserializeObject(JobArgs.Message); 75 | if (UserCollection?.EmailUser != "" || GroupCollection?.EmailGroup != "") 76 | { 77 | Locales = new Dictionary>(); 78 | JobArgs.DeliveryMechanisms = (DeliveryMechanisms)1; 79 | JobArgs.Message = MessageCollection?.EmailMessage; 80 | GetEmailUserDetails(JobArgs); 81 | JobPush(res); 82 | } 83 | if (UserCollection?.SMSUser != "" || GroupCollection?.SMSGroup != "") 84 | { 85 | JobArgs.DeliveryMechanisms = (DeliveryMechanisms)2; 86 | JobArgs.Message = MessageCollection?.SMSMessage; 87 | JobPush(res); 88 | } 89 | if (UserCollection?.SlackUser != "" || GroupCollection?.SlackGroup != "") 90 | { 91 | Locales = new Dictionary>(); 92 | JobArgs.DeliveryMechanisms = (DeliveryMechanisms)3; 93 | JobArgs.Message = MessageCollection?.SlackMessage; 94 | getSlackUser(); 95 | JobPush(res); 96 | } 97 | 98 | } 99 | else 100 | { 101 | Console.WriteLine("No Live version avaialble for :" + JobArgs.ObjId); 102 | } 103 | } 104 | } 105 | catch (Exception e) 106 | { 107 | Console.WriteLine(" Error in ReportInternal " + e.Message + e.StackTrace); 108 | } 109 | return new ReportInternalResponse() { }; 110 | } 111 | 112 | public void JobPush(EbObjectFetchLiveVersionResponse res) 113 | { 114 | try 115 | { 116 | EbObjectWrapper Live_ver = res.Data[0]; 117 | foreach (KeyValuePair> locale in Locales) 118 | { 119 | RepRes = ReportService.Get(new ReportRenderRequest 120 | { 121 | Refid = Live_ver.RefId, 122 | //RenderingUser = new User { FullName = "Machine User" }, 123 | //ReadingUser = locale.Value[0], 124 | Params = JobArgs.Params, 125 | SolnId = JobArgs.SolnId, 126 | UserAuthId = JobArgs.UserAuthId, 127 | UserId = JobArgs.UserId, 128 | WhichConsole = "uc" 129 | }); 130 | Console.WriteLine(locale.Key); 131 | Console.WriteLine("Inside MQService/ReportServiceInternal in SS \n After Report Render .Going to send email"); 132 | if (RepRes != null) 133 | { 134 | RepRes.StreamWrapper.Memorystream.Position = 0; 135 | foreach (User _u in locale.Value) 136 | { 137 | if (JobArgs.DeliveryMechanisms == DeliveryMechanisms.Email) 138 | PublishMail(_u.Email); 139 | else if (JobArgs.DeliveryMechanisms == DeliveryMechanisms.Slack) 140 | PublishSlackChat(_u.Email); 141 | //else if (JobArgs.DeliveryMechanisms == DeliveryMechanisms.Sms) 142 | // PublishSMS(_u.Email); 143 | } 144 | } 145 | //LocaleReport.Add(locale.Key, RepRes.ReportBytea); 146 | } 147 | } 148 | catch (Exception e) 149 | { 150 | Console.WriteLine(" Error in ReportInternal " + e.Message + e.StackTrace); 151 | } 152 | } 153 | 154 | public void GetEmailUserDetails(EbJobArguments JobArgs) 155 | { 156 | 157 | Console.WriteLine("----------Got Live Version Getting mail ids"); 158 | GetUserEmailsResponse mailres = SchedulersService.Get(new GetUserEmailsRequest() 159 | { 160 | UserIds = UserCollection.EmailUser, 161 | UserGroupIds = GroupCollection.EmailGroup 162 | }); 163 | Dictionary MailIds = mailres.UserEmails 164 | .Concat(mailres.UserGroupEmails) 165 | .GroupBy(d => d.Key) 166 | .ToDictionary(d => d.Key, d => d.First().Value); 167 | 168 | foreach (KeyValuePair u in MailIds) 169 | { 170 | User usr = GetUserObject(string.Format(TokenConstants.SUB_FORMAT, JobArgs.SolnId, u.Key, "uc")); 171 | if (usr != null) 172 | { 173 | if (Locales.ContainsKey(usr.Preference.Locale)) 174 | Locales[usr.Preference.Locale].Add(usr); 175 | else Locales.Add(usr.Preference.Locale, new List { usr }); 176 | } 177 | else 178 | { 179 | Console.WriteLine("Redis User Object is empty for : " + u.Value); 180 | } 181 | } 182 | Console.WriteLine("Number of locales : " + Locales.Count()); 183 | } 184 | 185 | public void getSlackUser() 186 | { 187 | 188 | List Users = new List(); 189 | string[] _slackUsers = (UserCollection.SlackUser + "," + UserCollection.SlackUser).Split(',').Distinct().ToArray(); 190 | _slackUsers = (GroupCollection.SlackGroup + "," + GroupCollection.SlackGroup).Split(',').Distinct().ToArray(); 191 | foreach (string slackid in _slackUsers) 192 | { 193 | User _u = new User { Email = slackid, Preference = new Preferences { TimeZone = "(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi", Locale = "en-US" } }; 194 | Users.Add(_u); 195 | } 196 | Locales.Add("en-US", Users); 197 | } 198 | 199 | public void PublishMail(string _mailId) 200 | { 201 | MessageProducer3.Publish(new EmailServicesRequest() 202 | { 203 | From = "request.from", 204 | To = _mailId, 205 | Cc = /*ebEmailTemplate.Cc.Split(",")*/ null, 206 | Bcc = /*ebEmailTemplate.Bcc.Split(",")*/ null, 207 | Subject = RepRes.ReportName + " - " + RepRes.CurrentTimestamp.ToShortDateString(), 208 | Message = JobArgs.Message, 209 | UserId = JobArgs.UserId, 210 | UserAuthId = JobArgs.UserAuthId, 211 | SolnId = JobArgs.SolnId, 212 | AttachmentReport = RepRes.ReportBytea, 213 | AttachmentName = RepRes.ReportName + " - " + RepRes.CurrentTimestamp.ToString("dd-MM-yy") + ".pdf" 214 | }); 215 | Console.WriteLine("Email to " + _mailId + " pushed....."); 216 | } 217 | public void PublishSlackChat(string _to) 218 | { 219 | MessageProducer3.Publish(new SlackCreateRequest 220 | { 221 | ObjId = JobArgs.ObjId, 222 | Params = JobArgs.Params, 223 | SolnId = JobArgs.SolnId, 224 | UserId = JobArgs.UserId, 225 | UserAuthId = JobArgs.UserAuthId, 226 | AttachmentReport = RepRes.ReportBytea, 227 | AttachmentName = RepRes.ReportName + " - " + RepRes.CurrentTimestamp.ToString("dd-MM-yy"), 228 | Message = JobArgs.Message, 229 | To = _to 230 | }); 231 | } 232 | 233 | public void PublishSMS(string _to) 234 | { 235 | MessageProducer3.Publish(new SMSPrepareRequest 236 | { 237 | ObjId = JobArgs.ObjId, 238 | Params = JobArgs.Params, 239 | SolnId = JobArgs.SolnId, 240 | UserId = JobArgs.UserId, 241 | UserAuthId = JobArgs.UserAuthId, 242 | Message = JobArgs.Message, 243 | To = _to 244 | }); 245 | } 246 | } 247 | } 248 | -------------------------------------------------------------------------------- /MQServices/SlackService.cs: -------------------------------------------------------------------------------- 1 | using ExpressBase.Common; 2 | using ExpressBase.Common.Constants; 3 | using ExpressBase.Common.Data; 4 | using ExpressBase.Common.Structures; 5 | using ExpressBase.Objects.Services; 6 | using ExpressBase.Objects.ServiceStack_Artifacts; 7 | using Newtonsoft.Json; 8 | using RestSharp; 9 | using ServiceStack; 10 | using ServiceStack.Messaging; 11 | using System; 12 | using System.Data.Common; 13 | 14 | namespace ExpressBase.ServiceStack.MQServices 15 | { 16 | 17 | 18 | [Restrict(InternalOnly = true)] 19 | public class SlackServiceInternal : EbMqBaseService 20 | { 21 | public SlackServiceInternal(IMessageProducer _mqp) : base(_mqp) { } 22 | // public string Post(SlackAuthRequest req) 23 | // { 24 | // EbConnectionFactory dbFactory = new EbConnectionFactory(req.SolnId, this.Redis); 25 | 26 | // if (req.IsNew) 27 | // { 28 | // try 29 | // { 30 | // string sql = "UPDATE eb_users SET slackjson = @slackjson WHERE id = @id RETURNING id"; 31 | 32 | // var id = dbFactory.DataDB.DoQuery(sql, new DbParameter[] { 33 | // dbFactory.DataDB.GetNewParameter("slackjson", EbDbTypes.Json,EbSerializers.Json_Serialize(req.SlackJson)), 34 | // dbFactory.DataDB.GetNewParameter("id", EbDbTypes.Int32, req.UserId) 35 | // }); 36 | // } 37 | 38 | // catch (Exception e) 39 | // { 40 | // return null; 41 | // } 42 | // } 43 | // else 44 | // { 45 | 46 | // } 47 | // return null; 48 | // } 49 | 50 | // public string Post(SlackPostMqRequest req) 51 | // { 52 | // EbConnectionFactory dbFactory = new EbConnectionFactory(req.TenantAccountId, this.Redis); 53 | 54 | // string sql = "SELECT slackjson FROM eb_users WHERE id = @id"; 55 | 56 | // var dt = dbFactory.DataDB.DoQuery(sql, new DbParameter[] { dbFactory.DataDB.GetNewParameter("id", EbDbTypes.Int32, req.UserId) }); 57 | // var json = dt.Rows[0][0]; 58 | // SlackJson slackJson = JsonConvert.DeserializeObject(json.ToString()); 59 | 60 | // var client = new RestClient("https://slack.com"); 61 | 62 | // if (req.PostType == 1) 63 | // { 64 | // var request = new RestRequest("api/files.upload", Method.POST); 65 | 66 | // request.AddParameter("token", slackJson.AccessToken); 67 | // request.AddParameter("user_id", slackJson.UserId); 68 | // request.AddParameter("team_id", slackJson.TeamId); 69 | // request.AddParameter("channels", req.Payload.Channel); 70 | // if (!string.IsNullOrEmpty(req.Payload.Text)) 71 | // request.AddParameter("content", req.Payload.Text); 72 | 73 | // if (req.Payload.SlackFile != null && req.Payload.SlackFile.FileByte != null && req.Payload.SlackFile.FileByte.Length > 0) 74 | // request.AddFile("file", req.Payload.SlackFile.FileByte, req.Payload.SlackFile.FileName, contentType: "multipart/form-data"); 75 | 76 | // //Execute the request 77 | // var res = client.ExecuteAsyncPost(request, SlackCallBack, "POST"); 78 | 79 | // } 80 | // else if (req.PostType == 0) 81 | // { 82 | // var request = new RestRequest("api/chat.postMessage", Method.POST); 83 | 84 | // request.AddParameter("token", slackJson.AccessToken); 85 | // request.AddParameter("channels", req.Payload.Channel); 86 | // request.AddParameter("user_id", slackJson.UserId); 87 | // request.AddParameter("team_id", slackJson.TeamId); 88 | // if (!string.IsNullOrEmpty(req.Payload.Text)) 89 | // request.AddParameter("text", req.Payload.Text); 90 | 91 | // //Execute the request 92 | // var res = client.ExecuteAsyncPost(request, SlackCallBack, "POST"); 93 | // } 94 | 95 | // return null; 96 | // } 97 | 98 | // private void AuthRes(IRestResponse arg1, RestRequestAsyncHandle arg2) 99 | // { 100 | 101 | // } 102 | 103 | // private void SlackCallBack(IRestResponse arg1, RestRequestAsyncHandle arg2) 104 | // { 105 | // //log response... 106 | // //throw new NotImplementedException(); 107 | // } 108 | //} 109 | public string Post(SlackCreateRequest request) 110 | { 111 | try 112 | { 113 | if (request.SolnId == CoreConstants.EXPRESSBASE) 114 | { 115 | //Console.WriteLine("Inside EmailService/EmailServiceInternal in SS Before Email To: " + request.To + "\nEmail Connections - infra: " + InfraConnectionFactory.EmailConnection.Capacity); 116 | this.InfraConnectionFactory.ChatConnection.Send(request.To, request.Message, request.AttachmentReport, request.AttachmentName); 117 | } 118 | else 119 | { 120 | base.EbConnectionFactory = new EbConnectionFactory(request.SolnId, this.Redis); 121 | //Console.WriteLine("Inside EmailService/EmailServiceInternal in SS \n Before Email \n To: " + request.To + "\nEmail Connections - solution: " + EbConnectionFactory.EmailConnection.Capacity); 122 | this.EbConnectionFactory.ChatConnection.Send(request.To, request.Message, request.AttachmentReport, request.AttachmentName); 123 | } 124 | 125 | // Console.WriteLine("Inside EmailService/EmailServiceInternal in SS \n After Email \nSend To:" + request.To); 126 | } 127 | catch (Exception e) 128 | { 129 | return e.Message; 130 | } 131 | return null; 132 | } 133 | 134 | } 135 | } 136 | 137 | 138 | 139 | //To a take Screenshot of a div (Javascript) 140 | //https://stackoverflow.com/questions/6887183/how-to-take-screenshot-of-a-div-with-javascript -------------------------------------------------------------------------------- /MQServices/SqlJobService.cs: -------------------------------------------------------------------------------- 1 | using ExpressBase.Objects.Services; 2 | using ServiceStack; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | 8 | namespace ExpressBase.ServiceStack.MQServices 9 | { 10 | [Restrict(InternalOnly = true)] 11 | public class SqlJobInternalService : EbMqBaseService 12 | { 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /NotoSerifMalayalam-VariableFont_wght.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ExpressBaseSystems/ExpressBase.ServiceStack/60e079fd6928986f90583fdab994815594e4d969/NotoSerifMalayalam-VariableFont_wght.ttf -------------------------------------------------------------------------------- /Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | using Microsoft.AspNetCore.Hosting; 7 | 8 | namespace ExpressBase.ServiceStack 9 | { 10 | public class Program 11 | { 12 | public static void Main(string[] args) 13 | { 14 | var host = new WebHostBuilder() 15 | .UseKestrel(options => { 16 | options.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(7); 17 | options.Limits.RequestHeadersTimeout = TimeSpan.FromMinutes(5); 18 | }) 19 | .UseContentRoot(Directory.GetCurrentDirectory()) 20 | .UseUrls(urls: "http://*:41600/") 21 | .UseStartup() 22 | .Build(); 23 | 24 | host.Run(); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "Eb": { 4 | "commandName": "Project", 5 | "launchBrowser": true, 6 | "launchUrl": "http://localhost:41600", 7 | "environmentVariables": { 8 | "ASPNETCORE_ENVIRONMENT": "Development" 9 | } 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ExpressBase.ServiceStack 2 | 3 | [EXPRESSbase](https://expressbase.com) is an open-source, Low-Code Rapid application development platform on the cloud for fast-growing SME (Small to Mid-sized business) to build & run internal process apps on web/mobile 10x faster. It is a truly multi-tenant, multi-database, cloud-native platform developed using micro-services architecture (not truly micro-services yet :D). 4 | 5 | EXPRESSbase has all the components to build huge, comprehensive internal business process apps - web & mobile. WebForm builder, MobilePage builder, Table/Chart/Map View builder, Dashboard builder, PDF builder, Email & SMS builders, Workflow/API builder, etc. It is still a work in progress, and a long way to go! 6 | 7 | **ExpressBase.ServiceStack** is the repository that holds the web-services as a micro-service (it is a mamoth currently, we will be breaking it down to smaller services). 8 | 9 | ### EXPRESSbase Micro-Services & Libraries 10 | 11 | * [ExpressBase.CoreBase](https://github.com/ExpressBaseSystems/ExpressBase.CoreBase) 12 | * [ExpressBase.Common](https://github.com/ExpressBaseSystems/ExpressBase.Common) 13 | * [ExpressBase.Objects](https://github.com/ExpressBaseSystems/ExpressBase.Objects) 14 | * [ExpressBase.ServiceStack](https://github.com/ExpressBaseSystems/ExpressBase.ServiceStack) 15 | * [ExpressBase.Web](https://github.com/ExpressBaseSystems/ExpressBase.Web) 16 | * [ExpressBase.AuthServer](https://github.com/ExpressBaseSystems/ExpressBase.AuthServer) 17 | * [ExpressBase.FileWeb](https://github.com/ExpressBaseSystems/ExpressBase.FileWeb) 18 | * [ExpressBase.FileServer](https://github.com/ExpressBaseSystems/ExpressBase.FileServer) 19 | * [ExpressBase.MessageQueue](https://github.com/ExpressBaseSystems/ExpressBase.MessageQueue) 20 | * [ExpressBase.ServerEvents](https://github.com/ExpressBaseSystems/ExpressBase.ServerEvents) 21 | * [ExpressBase.Scheduler](https://github.com/ExpressBaseSystems/ExpressBase.Scheduler) 22 | 23 | ## EXPRESSbase Low-Code Platform is Built With 24 | 25 | * [.NET Core](https://dotnet.microsoft.com/en-us/download/dotnet) 26 | * [ServiceStack.NET](https://servicestack.net/) 27 | * [PostgreSQL](https://www.postgresql.org/) 28 | * [Npgsql](https://www.npgsql.org/) 29 | * [Redis](https://redis.io/) - Caching & Server Events 30 | * [RabbitMQ](https://www.rabbitmq.com/) - Message Queue 31 | * [Quartz.NET](https://www.quartz-scheduler.net/) - Scheduler 32 | * [iTextSharp](https://github.com/itext/itextsharp) - Data-driven PDF generation 33 | * [Xamarin](https://dotnet.microsoft.com/en-us/apps/xamarin) - Mobile 34 | 35 | ## Authors / Contributors 36 | 37 | * **Suresh Balasubramanian** [sureba73](https://github.com/sureba73) 38 | * **Ahammed Unni Valiyapalam** [ahammedunni](https://github.com/ahammedunni) 39 | * **Febin Carlos** [febincarlos](https://github.com/febincarlos) 40 | * **Dona Jose Ullattil** [DonajoseUllattil](https://github.com/DonajoseUllattil) 41 | * **Amal K Dev** [amalkdev1355](https://github.com/amalkdev1355) 42 | 43 | See also the list of [contributors](https://github.com/ExpressBaseSystems/ExpressBase.Web/graphs/contributors) who participated in this project. 44 | 45 | ## License 46 | 47 | This project is licensed under the GNU General Public License v3.0 [LICENSE.md](LICENSE.md) file for details 48 | 49 | ## Acknowledgments 50 | 51 | * [Kerala Startup Mission](https://startupmission.kerala.gov.in/) 52 | * [NASSCOM 10k Startups](http://10000startups.com/) 53 | * [Start-Up Chile](https://startupchile.org/en/) 54 | -------------------------------------------------------------------------------- /Services/ApiConversionService.cs: -------------------------------------------------------------------------------- 1 | using ExpressBase.Common; 2 | using ExpressBase.Common.Data; 3 | using ExpressBase.Common.Structures; 4 | using ExpressBase.Objects; 5 | using ExpressBase.Objects.ServiceStack_Artifacts; 6 | using Newtonsoft.Json; 7 | using Newtonsoft.Json.Linq; 8 | using RestSharp; 9 | using RestSharp.Serialization.Json; 10 | using ServiceStack; 11 | using System; 12 | using System.Collections.Generic; 13 | using System.Data; 14 | using System.IO; 15 | using System.Linq; 16 | using System.Net; 17 | using System.Net.Http; 18 | using System.Threading.Tasks; 19 | using System.Web; 20 | using ResponseStatus = ServiceStack.ResponseStatus; 21 | 22 | namespace ExpressBase.ServiceStack.Services 23 | { 24 | [Authenticate] 25 | public class ApiConversionService : EbBaseService 26 | { 27 | private ResponseStatus _Responsestatus = new ResponseStatus(); 28 | EbDataSet ds = new EbDataSet(); 29 | 30 | public ApiConversionResponse Any(ApiConversionRequest request) 31 | { 32 | ApiConversionResponse resp = null; 33 | resp = start_get(request); 34 | return resp; 35 | } 36 | 37 | public IRestResponse Execute(ApiConversionRequest request) 38 | { 39 | List param = (request.Parameters != null) ? request.Parameters : new List(); 40 | string Url = (request.Method == ApiMethods.GET && param.Count > 0) ? ModifyUrl(request.Url, param) : request.Url; 41 | Uri uri = new Uri(Url); 42 | IRestResponse response = null; 43 | try 44 | { 45 | RestClient client = new RestClient(uri.GetLeftPart(UriPartial.Authority)); 46 | Method Method = (request.Method == ApiMethods.POST) ? RestSharp.Method.POST : RestSharp.Method.GET; 47 | RestRequest rest_req = new RestRequest(uri.PathAndQuery, Method); 48 | 49 | if (request.Headers != null && request.Headers.Any()) 50 | { 51 | foreach (ApiRequestHeader header in request.Headers) 52 | { 53 | rest_req.AddHeader(header.HeaderName, header.Value); 54 | } 55 | } 56 | 57 | if (uri.GetLeftPart(System.UriPartial.Authority).Contains(RoutingConstants.LIVEHOSTADDRESS) || 58 | uri.GetLeftPart(System.UriPartial.Authority).Contains(RoutingConstants.STAGEHOSTADDRESS)) 59 | { 60 | string _bt = this.Request.Headers["Authorization"]; 61 | _bt = _bt.Replace("Bearer ", ""); 62 | 63 | rest_req.AddHeader("bToken", _bt); 64 | rest_req.AddHeader("rToken", this.Request.Headers["rToken"]); 65 | } 66 | foreach (Param _param in param) 67 | { 68 | rest_req.AddParameter(_param.Name, _param.ValueTo); 69 | } 70 | response = client.Execute(rest_req); 71 | 72 | 73 | //using (var client = new HttpClient()) 74 | //{ 75 | // if (request.Headers != null && request.Headers.Any()) 76 | // { 77 | // foreach (ApiRequestHeader header in request.Headers) 78 | // { 79 | // client.DefaultRequestHeaders.Add(header.HeaderName, header.Value); 80 | // } 81 | // } 82 | 83 | // client.BaseAddress = new Uri(uri.GetLeftPart(System.UriPartial.Authority)); 84 | 85 | // if (uri.GetLeftPart(System.UriPartial.Authority).Contains(RoutingConstants.LIVEHOSTADDRESS) || 86 | // uri.GetLeftPart(System.UriPartial.Authority).Contains(RoutingConstants.STAGEHOSTADDRESS)) 87 | // { 88 | // client.BaseAddress.Add("bToken", this.Request.Headers["bToken"]); 89 | // client.DefaultRequestHeaders.Add("rToken", this.Request.Headers["rToken"]); 90 | // } 91 | // if (request.Method == ApiMethods.POST) 92 | // { 93 | // var parameters = param.Select(i => new { prop = i.Name, val = i.Value }) 94 | // .ToDictionary(x => x.prop, x => x.val); 95 | // response = client.PostAsync(uri.PathAndQuery, new FormUrlEncodedContent(parameters)).Result; 96 | // } 97 | // else if (request.Method == ApiMethods.GET) 98 | // { 99 | // response = client.GetAsync(uri.PathAndQuery).Result; 100 | // } 101 | //} 102 | } 103 | catch (Exception e) 104 | { 105 | throw e; 106 | } 107 | return response; 108 | } 109 | 110 | private string ModifyUrl(string longurl, List param) 111 | { 112 | var uriBuilder = new UriBuilder(longurl); 113 | var query = HttpUtility.ParseQueryString(uriBuilder.Query); 114 | foreach (Param i in param) 115 | query[i.Name] = i.Value; 116 | //query["action"] = "login1"; 117 | uriBuilder.Query = query.ToString(); 118 | longurl = uriBuilder.ToString(); 119 | return longurl; 120 | } 121 | 122 | private List GetParams(List Parameters) 123 | { 124 | return Parameters.Select(i => new Param { Name = i.ParamName, Type = i.Type.ToString(), Value = i.Value }) 125 | .ToList(); 126 | } 127 | 128 | private ApiConversionResponse start_get(ApiConversionRequest request) 129 | { 130 | ApiConversionResponse resp = new ApiConversionResponse(); 131 | IRestResponse response = null; 132 | try 133 | { 134 | response = Execute(request); 135 | string rawResponse = response.Content; 136 | JObject jsonObject = JObject.Parse(rawResponse); 137 | List Jproperty = null; 138 | Uri uri = new Uri(request.Url); 139 | if (uri.GetLeftPart(System.UriPartial.Authority).Contains(RoutingConstants.LIVEHOSTADDRESS) || 140 | uri.GetLeftPart(System.UriPartial.Authority).Contains(RoutingConstants.STAGEHOSTADDRESS)) 141 | { 142 | List Jproperty1 = jsonObject.Properties().Where(pp => pp.Name == "result").ToList(); 143 | try 144 | { 145 | JObject data = JObject.Parse(Jproperty1[0].Value.ToString()); 146 | Jproperty = data.Properties().Where(pp => pp.Name == "data").ToList(); 147 | } 148 | catch (Exception e) 149 | { 150 | Console.WriteLine(e.Message + e.StackTrace); 151 | Console.WriteLine(response.IsSuccessful + " " + response.StatusCode + " " + response.ErrorMessage + " " + response.Content); 152 | } 153 | } 154 | else 155 | Jproperty = jsonObject.Properties().Where(pp => pp.Value.Type == JTokenType.Array).ToList(); 156 | 157 | if (Jproperty != null) 158 | foreach (JProperty property in Jproperty) 159 | GetRecursive(property); 160 | } 161 | catch (Exception e) 162 | { 163 | Console.WriteLine(e.StackTrace); 164 | Console.WriteLine(e.Message); 165 | this._Responsestatus.Message = e.Message; 166 | } 167 | resp.dataset = ds; 168 | if (response != null) 169 | resp.statusCode = (int)response.StatusCode; 170 | return resp; 171 | } 172 | 173 | public EbDbTypes ConvertToEbdbType(JTokenType _type) 174 | { 175 | if (_type == JTokenType.Integer) 176 | return EbDbTypes.Int32; 177 | else if (_type == JTokenType.Boolean) 178 | return EbDbTypes.Boolean; 179 | else if (_type == JTokenType.Float) 180 | return EbDbTypes.Decimal; 181 | else if (_type == JTokenType.Date) 182 | return EbDbTypes.DateTime; 183 | else 184 | return EbDbTypes.String; 185 | } 186 | 187 | public object ConvertValueToEbdbType(JTokenType _type, JToken value) 188 | { 189 | if (_type == JTokenType.Integer) 190 | return Convert.ToInt32(value); 191 | else if (_type == JTokenType.Boolean) 192 | return Convert.ToBoolean(value); 193 | else if (_type == JTokenType.Float) 194 | return Convert.ToDecimal(value); 195 | else if (_type == JTokenType.Date) 196 | return Convert.ToDateTime(value); 197 | else 198 | return value.ToString(); 199 | } 200 | 201 | private void GetRecursive(JProperty property) 202 | { 203 | int k = 0; int i = 0; 204 | ds.Tables.Add(new EbDataTable(property.Name)); 205 | JTokenType _type; 206 | foreach (var children in property.Value.Children()) 207 | { 208 | if (i == 0) 209 | { 210 | ds.Tables[property.Name].Rows.Add(new EbDataRow()); 211 | foreach (var prop in children.Children().ToArray()) 212 | { 213 | if (prop.Value.Type == JTokenType.Array) 214 | GetRecursive(prop); 215 | else 216 | { 217 | if (prop.Name == "id" && Int32.TryParse((string)prop.Value, out _)) 218 | { 219 | _type = JTokenType.Integer; 220 | } 221 | else 222 | { 223 | _type = prop.Value.Type; 224 | } 225 | ds.Tables[property.Name].Columns.Add(new EbDataColumn { ColumnIndex = k, ColumnName = prop.Name.Replace(" ", "_"), Type = ConvertToEbdbType(_type) }); 226 | 227 | ds.Tables[property.Name].Rows[i][k++] = ConvertValueToEbdbType(_type, prop.Value); 228 | } 229 | } 230 | } 231 | else 232 | { 233 | ds.Tables[property.Name].Rows.Add(ds.Tables[property.Name].NewDataRow2()); 234 | k = 0; 235 | foreach (var prop in children.Children().ToArray()) 236 | { 237 | if (prop.Name == "id" && Int32.TryParse((string)prop.Value, out _)) 238 | { 239 | _type = JTokenType.Integer; 240 | } 241 | else 242 | { 243 | _type = prop.Value.Type; 244 | } 245 | ds.Tables[property.Name].Rows[i][k++] = ConvertValueToEbdbType(prop.Value.Type, prop.Value); 246 | } 247 | } 248 | i++; 249 | } 250 | } 251 | 252 | //public string ApiErrorHandling(int ) 253 | //{ 254 | 255 | //} 256 | } 257 | } 258 | -------------------------------------------------------------------------------- /Services/CalendarService.cs: -------------------------------------------------------------------------------- 1 | using ExpressBase.Common; 2 | using ExpressBase.Security; 3 | using ExpressBase.Common.Data; 4 | using ExpressBase.Common.Singletons; 5 | using ExpressBase.Common.Structures; 6 | using ExpressBase.Objects; 7 | using ExpressBase.Objects.Objects.DVRelated; 8 | using ExpressBase.Objects.ServiceStack_Artifacts; 9 | using ServiceStack; 10 | using System; 11 | using System.Collections.Generic; 12 | using System.Linq; 13 | using System.Text.RegularExpressions; 14 | using System.Threading.Tasks; 15 | using ExpressBase.Objects.Objects; 16 | using System.Globalization; 17 | 18 | namespace ExpressBase.ServiceStack.Services 19 | { 20 | [Authenticate] 21 | public class CalendarService : EbBaseService 22 | { 23 | public CalendarService(IEbConnectionFactory _dbf) : base(_dbf) { } 24 | 25 | private ResponseStatus _Responsestatus = new ResponseStatus(); 26 | 27 | private User _user = new User(); 28 | 29 | private string PreviousGroupingText = string.Empty; 30 | 31 | private EbDataSet dataset = new EbDataSet(); 32 | 33 | private EbDataTable _formattedTable = null; 34 | 35 | private EbCalendarView _dV = null; 36 | 37 | private int j = -1; 38 | 39 | private CultureInfo _user_culture = null; 40 | 41 | private bool Modifydv = true; 42 | 43 | [CompressResponse] 44 | public CalendarDataResponse Any(CalendarDataRequest request) 45 | { 46 | try 47 | { 48 | this.Log.Info("data request"); 49 | Modifydv = request.ModifyDv; 50 | _dV = request.CalendarObj; 51 | this._user = request.UserInfo; 52 | 53 | CalendarDataResponse dsresponse = null; 54 | var _ds = this.Redis.Get(request.RefId); 55 | 56 | if (_ds == null) 57 | { 58 | var myService = base.ResolveService(); 59 | var result = (EbObjectParticularVersionResponse)myService.Get(new EbObjectParticularVersionRequest() { RefId = request.RefId }); 60 | _ds = EbSerializers.Json_Deserialize(result.Data[0].Json); 61 | Redis.Set(request.RefId, _ds); 62 | } 63 | if (_ds.FilterDialogRefId != string.Empty) 64 | { 65 | var _dsf = this.Redis.Get(_ds.FilterDialogRefId); 66 | if (_dsf == null) 67 | { 68 | var myService = base.ResolveService(); 69 | var result = (EbObjectParticularVersionResponse)myService.Get(new EbObjectParticularVersionRequest() { RefId = _ds.FilterDialogRefId }); 70 | _dsf = EbSerializers.Json_Deserialize(result.Data[0].Json); 71 | Redis.Set(_ds.FilterDialogRefId, _dsf); 72 | } 73 | if (request.Params == null) 74 | request.Params = _dsf.GetDefaultParams(); 75 | } 76 | string _sql = string.Empty; 77 | string tempsql = string.Empty; 78 | 79 | bool _isPaged = false; 80 | if (_ds != null) 81 | { 82 | string _c = string.Empty; 83 | _sql = _ds.Sql; 84 | } 85 | var parameters = DataHelper.GetParams(this.EbConnectionFactory.ObjectsDB, _isPaged, request.Params,0, 0); 86 | EbDataSet _dataset = null; 87 | try 88 | { 89 | _dataset = this.EbConnectionFactory.ObjectsDB.DoQueries(_sql, parameters.ToArray()); 90 | } 91 | catch (Exception e) 92 | { 93 | Log.Info("Datviz Qurey Exception........." + e.StackTrace); 94 | Log.Info("Datviz Qurey Exception........." + e.Message); 95 | this._Responsestatus.Message = e.Message; 96 | } 97 | if (GetLogEnabled(request.RefId)) 98 | { 99 | TimeSpan T = _dataset.EndTime - _dataset.StartTime; 100 | InsertExecutionLog(_dataset.RowNumbers, T, _dataset.StartTime, request.UserId, request.Params, request.RefId); 101 | } 102 | int _recordsTotal = 0, _recordsFiltered = 0; 103 | if (_isPaged) 104 | { 105 | Int32.TryParse(_dataset.Tables[_dataset.Tables.Count - 1].Rows[0][0].ToString(), out _recordsTotal); 106 | Int32.TryParse(_dataset.Tables[_dataset.Tables.Count - 1].Rows[0][0].ToString(), out _recordsFiltered); 107 | } 108 | _recordsTotal = (_recordsTotal > 0) ? _recordsTotal : _dataset.Tables[_dataset.Tables.Count - 1].Rows.Count; 109 | _recordsFiltered = (_recordsFiltered > 0) ? _recordsFiltered : _dataset.Tables[_dataset.Tables.Count - 1].Rows.Count; 110 | //-- 111 | PrePrcessorReturn ReturnObj = null; 112 | if (_dataset.Tables.Count > 0 && _dV != null) 113 | { 114 | ReturnObj = PreProcessing(_dataset, request.Params); 115 | } 116 | 117 | List _permission = new List(); 118 | dsresponse = new CalendarDataResponse 119 | { 120 | Data = (ReturnObj?.rows != null) ? ReturnObj.rows : _dataset.Tables[0].Rows, 121 | FormattedData = (ReturnObj?.FormattedTable != null) ? ReturnObj.FormattedTable.Rows : null, 122 | CalendarReturnObj = _dV, 123 | ResponseStatus = this._Responsestatus 124 | }; 125 | this.Log.Info(" dataviz dataresponse*****" + dsresponse.Data); 126 | EbSerializers.Json_Serialize(dsresponse); 127 | return dsresponse; 128 | } 129 | catch (Exception e) 130 | { 131 | Log.Info("Datviz service Exception........." + e.StackTrace); 132 | Log.Info("Datviz service Exception........." + e.Message); 133 | this._Responsestatus.Message = e.Message; 134 | } 135 | return null; 136 | } 137 | 138 | public PrePrcessorReturn PreProcessing(EbDataSet _dataset, List Parameters) 139 | { 140 | try 141 | { 142 | this._user_culture = CultureHelper.GetSerializedCultureInfo(this._user.Preference.Locale).GetCultureInfo(); 143 | 144 | var colCount = _dataset.Tables[0].Columns.Count; 145 | 146 | Globals globals = new Globals(); 147 | if (Modifydv) 148 | this.CreateCustomcolumn(ref _dataset, Parameters); 149 | else 150 | this.CreateCustomcolumn4EbDataSet(ref _dataset, Parameters); 151 | _formattedTable = _dataset.Tables[0].GetEmptyTable(); 152 | _formattedTable.Columns.Add(_formattedTable.NewDataColumn(_dV.Columns.Count, "serial", EbDbTypes.Int32)); 153 | RowColletion rows = _dataset.Tables[0].Rows; 154 | for (int i = 0; i < rows.Count; i++) 155 | { 156 | CreateFormattedTable(rows[i], i ); 157 | } 158 | return new PrePrcessorReturn { FormattedTable = _formattedTable, rows = rows }; 159 | } 160 | catch (Exception e) 161 | { 162 | Log.Info("Before PreProcessing in datatable Exception........." + e.StackTrace); 163 | Log.Info("Before PreProcessing in datatable Exception........." + e.Message); 164 | this._Responsestatus.Message = e.Message; 165 | } 166 | return null; 167 | } 168 | 169 | public void CreateCustomcolumn(ref EbDataSet _dataset, List Parameters) 170 | { 171 | var dates = new List(); 172 | int index = _dV.Columns.Count; 173 | for (var date = new DateTime(2015, 3, 1); date.Month == 3; date = date.AddDays(1)) 174 | { 175 | _dataset.Tables[0].Columns.Add(new EbDataColumn { ColumnIndex = index, ColumnName = date.Date.ToString(), Type = EbDbTypes.String }); 176 | _dV.Columns.Add(new DVStringColumn { Data = index++, Name = date.ToString("dd-MM-yyyy"), sTitle = date.ToString("ddd")[0] + "
" + date.ToString("dd"), Type = EbDbTypes.String, IsCustomColumn = true , bVisible=true}); 177 | } 178 | } 179 | 180 | public void CreateCustomcolumn4EbDataSet(ref EbDataSet _dataset, List Parameters) 181 | { 182 | var dates = new List(); 183 | int index = _dV.Columns.Count; 184 | for (var date = new DateTime(2015, 3, 1); date.Month == 3; date = date.AddDays(1)) 185 | { 186 | _dataset.Tables[0].Columns.Add(new EbDataColumn { ColumnIndex = index, ColumnName = date.Date.ToString(), Type = EbDbTypes.String }); 187 | } 188 | } 189 | 190 | public void CreateFormattedTable(EbDataRow row, int i) 191 | { 192 | try 193 | { 194 | object TempGroupingText = row[2].ToString();//keycolumn 195 | if (TempGroupingText.Equals(PreviousGroupingText) == false) 196 | { 197 | j++; 198 | PreviousGroupingText = TempGroupingText.ToString(); 199 | _formattedTable.Rows.Add(_formattedTable.NewDataRow2()); 200 | _formattedTable.Rows[j][_formattedTable.Columns.Count - 1] = j + 1;//serial 201 | object unformated = Convert.ToDateTime( row[7]).ToString("dd-MM-yyyy");// date column date 202 | foreach (DVBaseColumn col in _dV.Columns) 203 | { 204 | var cults = col.GetColumnCultureInfo(this._user_culture); 205 | if (col.IsCustomColumn) 206 | { 207 | if(unformated.ToString() == col.Name) 208 | { 209 | _formattedTable.Rows[j][col.Data] = row[4].ToString() + " , " + row[5].ToString() + " , " + row[6].ToString(); 210 | } 211 | } 212 | else 213 | { 214 | if (col.Type == EbDbTypes.Date || col.Type == EbDbTypes.DateTime) 215 | _formattedTable.Rows[j][col.Data] = Convert.ToDateTime(row[col.Data]).ToString("d", cults.DateTimeFormat); 216 | else 217 | _formattedTable.Rows[j][col.Data] = row[col.Data]; 218 | 219 | } 220 | } 221 | } 222 | else 223 | { 224 | object unformated = Convert.ToDateTime(row[7]).ToString("dd-MM-yyyy");// date column 225 | foreach (DVBaseColumn col in _dV.Columns) 226 | { 227 | if (col.IsCustomColumn) 228 | { 229 | if (unformated.ToString() == col.Name) 230 | { 231 | _formattedTable.Rows[j][col.Data] = row[4].ToString() + " , " + row[5].ToString() + " , " + row[6].ToString(); 232 | } 233 | } 234 | } 235 | } 236 | } 237 | catch (Exception e) 238 | { 239 | Log.Info("PreProcessing in datatable Exception........." + e.StackTrace); 240 | Log.Info("PreProcessing in datatable Exception........." + e.Message); 241 | this._Responsestatus.Message = e.Message; 242 | } 243 | 244 | } 245 | } 246 | } 247 | -------------------------------------------------------------------------------- /Services/EbBluePrintServices.cs: -------------------------------------------------------------------------------- 1 | using ExpressBase.Common; 2 | using ExpressBase.Common.Data; 3 | using ExpressBase.Common.Extensions; 4 | using ExpressBase.Common.Structures; 5 | using ExpressBase.Objects.ServiceStack_Artifacts; 6 | using ServiceStack; 7 | using System; 8 | using System.Collections.Generic; 9 | using System.Data.Common; 10 | using System.IO; 11 | using System.Linq; 12 | using System.Threading.Tasks; 13 | 14 | namespace ExpressBase.ServiceStack.Services 15 | { 16 | [Authenticate] 17 | public class EbBluePrintServices : EbBaseService 18 | { 19 | public EbBluePrintServices(IEbConnectionFactory _dbf) : base(_dbf) { } 20 | 21 | public SaveBluePrintResponse Post(SaveBluePrintRequest svgreq) 22 | { 23 | SaveBluePrintResponse svgres = new SaveBluePrintResponse(); 24 | try 25 | { 26 | 27 | string sql = @"INSERT INTO eb_blueprint(svgtext,bgimg_bytea,bp_meta) 28 | VALUES( 29 | :svgst, 30 | :imgbytea, 31 | :bpmeta 32 | )RETURNING id;"; 33 | 34 | DbParameter[] parameters = { 35 | this.EbConnectionFactory.DataDB.GetNewParameter("svgst", EbDbTypes.String, svgreq.Txtsvg), 36 | this.EbConnectionFactory.DataDB.GetNewParameter("imgbytea", EbDbTypes.Bytea, svgreq.BgFile ), 37 | this.EbConnectionFactory.DataDB.GetNewParameter("bpmeta", EbDbTypes.String, svgreq.MetaBluePrint) 38 | //this.EbConnectionFactory.DataDB.GetNewParameter("svgst", EbDbTypes.String, (String.IsNullOrEmpty(svgreq.Txtsvg))?null:svgreq.Txtsvg), 39 | //this.EbConnectionFactory.DataDB.GetNewParameter("imgbytea", EbDbTypes.Bytea, (svgreq.BgFile != null && svgreq.BgFile.Length > 0)?null:svgreq.BgFile ), 40 | //this.EbConnectionFactory.DataDB.GetNewParameter("bpmeta", EbDbTypes.String, String.IsNullOrEmpty(svgreq.MetaBluePrint)?null:svgreq.MetaBluePrint) 41 | }; 42 | 43 | EbDataTable dt = this.EbConnectionFactory.DataDB.DoQuery(sql, parameters); 44 | svgres.Bprntid = Convert.ToInt32(dt.Rows[0][0]); 45 | 46 | 47 | } 48 | catch (Exception e) 49 | { 50 | Console.WriteLine("Exception: " + e.Message + e.StackTrace); 51 | } 52 | return svgres; 53 | } 54 | 55 | public RetriveBluePrintResponse Post(RetriveBluePrintRequest rtsvg) 56 | { 57 | RetriveBluePrintResponse rsv = new RetriveBluePrintResponse(); 58 | try 59 | { 60 | 61 | string sql1 = @"SELECT 62 | svgtext, 63 | bgimg_bytea, 64 | bp_meta 65 | FROM 66 | eb_blueprint 67 | WHERE 68 | id=:svgid"; 69 | DbParameter[] param = 70 | { 71 | this.EbConnectionFactory.DataDB.GetNewParameter("svgid", EbDbTypes.Int32, rtsvg.Idno) 72 | }; 73 | EbDataTable dt = this.EbConnectionFactory.DataDB.DoQuery(sql1, param); 74 | if (dt.Rows.Count > 0) 75 | { 76 | rsv.SvgPolyData = dt.Rows[0][0].ToString(); 77 | var fileBase64Data = Convert.ToBase64String((byte[])(dt.Rows[0][1])); 78 | //rsv.FileDataURL = fileBase64Data; 79 | rsv.FileDataURL = string.Format("data:image/png;base64,{0}", fileBase64Data); 80 | rsv.BpMeta = dt.Rows[0][2].ToString(); 81 | } 82 | } 83 | catch (Exception e) 84 | { 85 | Console.WriteLine("Exception: " + e.Message + e.StackTrace); 86 | } 87 | 88 | return rsv; 89 | } 90 | 91 | public UpdateBluePrint_DevResponse Post(UpdateBluePrint_DevRequest upblresp) { 92 | UpdateBluePrint_DevResponse upblreq = new UpdateBluePrint_DevResponse(); 93 | 94 | string tem = string.Empty; 95 | List p = new List(); 96 | try 97 | { 98 | if (upblresp.BluePrintID > 0) 99 | { 100 | if (upblresp.BP_FormData_Dict.Count > 0) 101 | { 102 | foreach (var dct in upblresp.BP_FormData_Dict) 103 | { 104 | tem += dct.Key + "=" + ":" + dct.Key + ","; 105 | p.Add(this.EbConnectionFactory.DataDB.GetNewParameter(":" + dct.Key, EbDbTypes.String, dct.Value)); 106 | } 107 | 108 | tem = tem.Remove(tem.Length - 1, 1); 109 | string sql = String.Format(@"UPDATE 110 | eb_blueprint 111 | SET 112 | {0} 113 | WHERE 114 | id=:bpid", tem 115 | ); 116 | 117 | p.Add(this.EbConnectionFactory.DataDB.GetNewParameter("bpid", EbDbTypes.Int32, upblresp.BluePrintID)); 118 | DbParameter[] parameters = p.ToArray(); 119 | int dt = this.EbConnectionFactory.DataDB.DoNonQuery(sql, parameters); 120 | if (dt > 0) 121 | { 122 | upblreq.Bprntid = upblresp.BluePrintID; 123 | } 124 | } 125 | } 126 | } 127 | catch (Exception e) 128 | { 129 | Console.WriteLine("Exception: " + e.Message + e.StackTrace); 130 | } 131 | return upblreq; 132 | } 133 | 134 | 135 | 136 | 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /Services/EbFileDownloadService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Net; 5 | using ExpressBase.Common.Constants; 6 | using ServiceStack; 7 | using ExpressBase.Common; 8 | using ExpressBase.Common.Data; 9 | using ExpressBase.Common.Enums; 10 | using ExpressBase.Objects.ServiceStack_Artifacts; 11 | using ExpressBase.Common.ServiceClients; 12 | using ExpressBase.Common.EbServiceStack.ReqNRes; 13 | using ExpressBase.Common.ServiceStack.ReqNRes; 14 | using System.Linq; 15 | using System.Data.Common; 16 | using ExpressBase.Common.Structures; 17 | using ServiceStack.Messaging; 18 | using ExpressBase.Objects.Helpers; 19 | using static ExpressBase.Objects.Helpers.DownloadsPageHelper; 20 | 21 | namespace ExpressBase.ServiceStack.Services 22 | { 23 | public class EbFileDownloadService : EbBaseService 24 | { 25 | public string UserName { get; set; } 26 | public string Password { private get; set; } 27 | public string Host { get; set; } 28 | public List> Files { get; set; } 29 | 30 | public EbFileDownloadService(IEbConnectionFactory _dbf, IEbStaticFileClient _sfc, IMessageProducer _mqp, IMessageQueueClient _mqc) 31 | : base(_dbf, _sfc, _mqp, _mqc) { } 32 | 33 | private void GetFileNamesFromDb() 34 | { 35 | int CustomerId = 0; 36 | string UploadPath = @"Softfiles_L/"; 37 | // string ImageTableQuery_deprecated = @" 38 | //SELECT 39 | // customervendor.id, customervendor.accountcode, customervendor.imageid, vddicommentry.filename 40 | //FROM 41 | // customervendor, vddicommentry 42 | //WHERE 43 | // vddicommentry.patientid = (customervendor.prehead || customervendor.accountcode) 44 | //ORDER BY 45 | // vddicommentry.filename"; 46 | string ImageTableQuery = @" SELECT 47 | vddicommentry.customers_id, vddicommentry.imageid, vddicommentry.filename 48 | FROM 49 | vddicommentry 50 | ORDER BY 51 | vddicommentry.filename"; 52 | string _imageId = string.Empty, _fileName = string.Empty; 53 | 54 | var table = this.EbConnectionFactory.DataDB.DoQuery(ImageTableQuery); 55 | foreach (EbDataRow row in table.Rows) 56 | { 57 | CustomerId = (int)row[0]; 58 | _imageId = row[1].ToString(); 59 | _fileName = row[2].ToString(); 60 | Files.Add(new KeyValuePair(CustomerId, UploadPath + _imageId + "/DICOM/" + _fileName)); 61 | } 62 | } 63 | 64 | public bool AddEntry(string fname, int CustomerId) 65 | { 66 | int res = 0; 67 | 68 | try 69 | { 70 | string AddQuery = @"INSERT INTO 71 | eb_image_migration_counter(filename, customer_id) 72 | VALUES 73 | (@fname, @cid);"; 74 | DbParameter[] MapParams = 75 | { 76 | this.EbConnectionFactory.DataDB.GetNewParameter("cid", EbDbTypes.Int32, CustomerId), 77 | this.EbConnectionFactory.DataDB.GetNewParameter("fname", EbDbTypes.String, fname), 78 | }; 79 | res = this.EbConnectionFactory.DataDB.DoNonQuery(AddQuery, MapParams); 80 | } 81 | catch (Exception e) 82 | { 83 | Log.Error("Counter: " + e.Message); 84 | } 85 | return res > 0; 86 | } 87 | 88 | [Authenticate] 89 | public void Post(FileDownloadRequestObject req) 90 | { 91 | string FilerefId = string.Empty; 92 | 93 | Files = new List>(); 94 | 95 | GetFileNamesFromDb(); 96 | 97 | Console.WriteLine("Got data from Vddi Comentry"); 98 | 99 | GetImageFtpRequest getImageFtp = new GetImageFtpRequest(); 100 | 101 | getImageFtp.AddAuth(req.UserId, req.SolnId, this.FileClient.BearerToken, this.FileClient.RefreshToken); 102 | 103 | if (Files.Count > 0) 104 | { 105 | foreach (KeyValuePair file in Files) 106 | { 107 | if (!file.Value.Equals(string.Empty)) 108 | { 109 | getImageFtp.FileUrl = file; 110 | this.MessageProducer3.Publish(getImageFtp); 111 | 112 | AddEntry(fname: file.Value.SplitOnLast('/').Last(), CustomerId: file.Key); 113 | } 114 | } 115 | } 116 | } 117 | 118 | // Downloads page 119 | public GetDownloadFileResponse Get(GetDownloadFileRequest request) 120 | { 121 | GetDownloadFileResponse response = new GetDownloadFileResponse(); 122 | 123 | if (request.IsGetAll) 124 | { 125 | response.AllDownloadObjects = (new DownloadsPageHelper()).GetAllDownloadFiles(this.EbConnectionFactory.DataDB, request.UserId, GetUserObject(request.UserAuthId)?.Preference); 126 | } 127 | else 128 | { 129 | response.FileDownloadObject = (new DownloadsPageHelper()).GetDownloadFile(this.EbConnectionFactory.DataDB, request.Id); 130 | 131 | if (response.FileDownloadObject?.FileBytea != null) 132 | { 133 | (new DownloadsPageHelper()).DeleteDownloadFile(this.EbConnectionFactory.DataDB, request.Id); 134 | } 135 | } 136 | 137 | return response; 138 | } 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /Services/EbMeetingService.cs: -------------------------------------------------------------------------------- 1 | using ExpressBase.Common; 2 | using ExpressBase.Common.Constants; 3 | using ExpressBase.Common.Data; 4 | using ExpressBase.Common.Extensions; 5 | using ExpressBase.Common.LocationNSolution; 6 | using ExpressBase.Common.Objects; 7 | using ExpressBase.Common.Structures; 8 | using ExpressBase.Security; 9 | using ExpressBase.Objects; 10 | using ExpressBase.Objects.Objects; 11 | using ExpressBase.Objects.Objects.DVRelated; 12 | using ExpressBase.Objects.ServiceStack_Artifacts; 13 | using ExpressBase.Objects.WebFormRelated; 14 | using Jurassic; 15 | using Jurassic.Library; 16 | using Microsoft.CodeAnalysis.CSharp.Scripting; 17 | using Microsoft.CodeAnalysis.Scripting; 18 | using Newtonsoft.Json; 19 | using ServiceStack; 20 | using ServiceStack.Messaging; 21 | using System; 22 | using System.Collections.Generic; 23 | using System.Data.Common; 24 | using System.Linq; 25 | 26 | namespace ExpressBase.ServiceStack.Services 27 | { 28 | [Authenticate] 29 | public class EbMeetingService : EbBaseService 30 | { 31 | public EbMeetingService(IEbConnectionFactory _dbf, IMessageProducer _mqp) : base(_dbf, _mqp) { } 32 | 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Services/FileOperationServices.cs: -------------------------------------------------------------------------------- 1 | using ExpressBase.Common; 2 | using ExpressBase.Common.Data; 3 | using ExpressBase.Common.EbServiceStack.ReqNRes; 4 | using ExpressBase.Common.ServiceClients; 5 | using ExpressBase.Common.Structures; 6 | using ExpressBase.Objects.ServiceStack_Artifacts; 7 | using Newtonsoft.Json; 8 | using ServiceStack; 9 | using ServiceStack.Messaging; 10 | using System; 11 | using System.Collections.Generic; 12 | using System.Data.Common; 13 | using System.Linq; 14 | using System.Text; 15 | using System.Threading.Tasks; 16 | 17 | namespace ExpressBase.ServiceStack.Services 18 | { 19 | public class FileOperationServices : EbBaseService 20 | { 21 | public FileOperationServices(IEbConnectionFactory _dbf, IEbStaticFileClient _sfc, IMessageProducer _mqp, IMessageQueueClient _mqc) : base(_dbf, _sfc, _mqp, _mqc) 22 | { 23 | } 24 | 25 | [Authenticate] 26 | public FileCategoryChangeResponse Post(FileCategoryChangeRequest request) 27 | { 28 | int result; 29 | //string sql = EbConnectionFactory.DataDB.EB_FILECATEGORYCHANGE; 30 | try 31 | { 32 | Console.WriteLine("Cat: " + request.Category); 33 | Console.WriteLine("Ids: " + request.FileRefId.Join(",")); 34 | 35 | string slectquery = EbConnectionFactory.DataDB.EB_FILECATEGORYCHANGE; 36 | DbParameter[] parameters = 37 | { 38 | this.EbConnectionFactory.DataDB.GetNewParameter("ids", EbDbTypes.String, request.FileRefId.Join(",")), 39 | }; 40 | 41 | EbDataTable dt = this.EbConnectionFactory.DataDB.DoQuery(slectquery, parameters); 42 | 43 | StringBuilder dystring = new StringBuilder(); 44 | 45 | foreach (EbDataRow row in dt.Rows) 46 | { 47 | int id = Convert.ToInt32(row["id"]); 48 | 49 | EbFileMeta meta; 50 | try 51 | { 52 | meta = JsonConvert.DeserializeObject(row["tags"].ToString()); 53 | if (meta == null) 54 | meta = new EbFileMeta(); 55 | } 56 | catch (Exception ex) 57 | { 58 | Console.WriteLine(ex.Message); 59 | meta = new EbFileMeta(); 60 | } 61 | 62 | meta.Category.Clear(); 63 | meta.Category.Add(request.Category); 64 | string serialized = JsonConvert.SerializeObject(meta); 65 | dystring.Append(string.Format("UPDATE eb_files_ref SET tags='{0}' WHERE id={1};", serialized, id)); 66 | } 67 | 68 | result = this.EbConnectionFactory.DataDB.DoNonQuery(dystring.ToString()); 69 | } 70 | catch (Exception ex) 71 | { 72 | result = 0; 73 | Console.BackgroundColor = ConsoleColor.Red; 74 | Console.WriteLine("Exception while updating Category:" + ex.Message); 75 | } 76 | 77 | return new FileCategoryChangeResponse { Status = (result > 0) ? true : false }; 78 | } 79 | 80 | public FileUploadResponse Any(FileUploadInternalRequest request) 81 | { 82 | FileUploadResponse response= this.FileClient.Post(new FileUploadRequest 83 | { 84 | FileByte = request.FileByte, 85 | FileCategory = request.FileCategory, 86 | FileDetails = request.FileDetails, 87 | SolnId = request.SolnId, 88 | UserAuthId = request.UserAuthId, 89 | UserId = request.UserId, 90 | WhichConsole = request.WhichConsole 91 | }); 92 | return response; 93 | } 94 | } 95 | } 96 | 97 | -------------------------------------------------------------------------------- /Services/FilterDialogService.cs: -------------------------------------------------------------------------------- 1 | using ExpressBase.Common; 2 | using ExpressBase.Common.Data; 3 | using ExpressBase.Objects; 4 | using ExpressBase.Objects.ServiceStack_Artifacts; 5 | using ServiceStack; 6 | using System; 7 | using System.Collections.Generic; 8 | using System.Linq; 9 | using System.Text.RegularExpressions; 10 | using System.Threading.Tasks; 11 | 12 | namespace ExpressBase.ServiceStack.Services 13 | { 14 | [Authenticate] 15 | public class FilterDialogService :EbBaseService 16 | { 17 | public FilterDialogService(IEbConnectionFactory _dbf) : base(_dbf) { } 18 | 19 | [CompressResponse] 20 | public FDDataResponse Any(FDDataRequest request) 21 | { 22 | this.Log.Info("data request"); 23 | 24 | FDDataResponse dsresponse = null; 25 | 26 | var _ds = this.Redis.Get(request.RefId); 27 | string _sql = string.Empty; 28 | 29 | if (_ds == null) 30 | { 31 | var myService = base.ResolveService(); 32 | var result = (EbObjectParticularVersionResponse)myService.Get(new EbObjectParticularVersionRequest() { RefId = request.RefId }); 33 | _ds = EbSerializers.Json_Deserialize(result.Data[0].Json); 34 | Redis.Set(request.RefId, _ds); 35 | } 36 | if (_ds.FilterDialogRefId != string.Empty && _ds.FilterDialogRefId != null) 37 | { 38 | var _dsf = this.Redis.Get(_ds.FilterDialogRefId); 39 | if (_dsf == null) 40 | { 41 | var myService = base.ResolveService(); 42 | var result = (EbObjectParticularVersionResponse)myService.Get(new EbObjectParticularVersionRequest() { RefId = _ds.FilterDialogRefId }); 43 | _dsf = EbSerializers.Json_Deserialize(result.Data[0].Json); 44 | Redis.Set(_ds.FilterDialogRefId, _dsf); 45 | } 46 | if (request.Params == null) 47 | request.Params = _dsf.GetDefaultParams(); 48 | } 49 | 50 | if (_ds != null) 51 | { 52 | string _c = string.Empty; 53 | 54 | if (request.TFilters != null && request.TFilters.Count > 0) 55 | { 56 | foreach (TFilters _dic in request.TFilters) 57 | { 58 | var op = _dic.Operator; var col = _dic.Column; var val = _dic.Value; 59 | if (EbConnectionFactory.ObjectsDB.Vendor == DatabaseVendors.MYSQL) 60 | { 61 | if (op == "x*") 62 | _c += string.Format("AND CAST(LOWER({0}) AS CHAR(200)) LIKE LOWER('{1}%') ", col, val); 63 | else if (op == "*x") 64 | _c += string.Format("AND CAST(LOWER({0}) AS CHAR(200)) LIKE LOWER('%{1}') ", col, val); 65 | else if (op == "*x*") 66 | _c += string.Format("AND CAST(LOWER({0}) AS CHAR(200)) LIKE LOWER('%{1}%') ", col, val); 67 | else if (op == "=") 68 | _c += string.Format("AND CAST(LOWER({0}) AS CHAR(200)) = LOWER('{1}') ", col, val); 69 | else 70 | _c += string.Format("AND {0} {1} '{2}' ", col, op, val); 71 | } 72 | else 73 | { 74 | if (op == "x*") 75 | _c += string.Format("AND LOWER({0})::text LIKE LOWER('{1}%') ", col, val); 76 | else if (op == "*x") 77 | _c += string.Format("AND LOWER({0})::text LIKE LOWER('%{1}') ", col, val); 78 | else if (op == "*x*") 79 | _c += string.Format("AND LOWER({0})::text LIKE LOWER('%{1}%') ", col, val); 80 | else if (op == "=") 81 | _c += string.Format("AND LOWER({0}::text) = LOWER('{1}') ", col, val); 82 | else 83 | _c += string.Format("AND {0} {1} '{2}' ", col, op, val); 84 | } 85 | 86 | } 87 | } 88 | if (this.EbConnectionFactory.ObjectsDB.Vendor == DatabaseVendors.PGSQL) 89 | _sql = _ds.Sql.Replace("@and_search", _c); 90 | else 91 | _sql = _ds.Sql.Replace(":and_search", _c); 92 | } 93 | bool _isPaged = false; 94 | if (this.EbConnectionFactory.ObjectsDB.Vendor == DatabaseVendors.PGSQL) 95 | { 96 | _sql = _sql.Replace("@orderby", 97 | (string.IsNullOrEmpty(request.OrderByCol)) ? "id" : string.Format("{0} {1}", request.OrderByCol, ((request.OrderByDir == 2) ? "DESC" : "ASC"))); 98 | 99 | _isPaged = (_sql.ToLower().Contains("@offset") && _sql.ToLower().Contains("@limit")); 100 | 101 | //var parameters = DataHelper.GetParams(this.EbConnectionFactory, _isPaged, request.Params, request.Length, request.Start); 102 | if (request.Params == null) 103 | _sql = _sql.Replace("@id", "0"); 104 | } 105 | else 106 | { 107 | _sql = _sql.Replace(":orderby", 108 | (string.IsNullOrEmpty(request.OrderByCol)) ? "id" : string.Format("{0} {1}", request.OrderByCol, ((request.OrderByDir == 2) ? "DESC" : "ASC"))); 109 | 110 | _isPaged = (_sql.ToLower().Contains(":offset") && _sql.ToLower().Contains(":limit")); 111 | 112 | 113 | if (request.Params == null) 114 | _sql = _sql.Replace(":id", "0"); 115 | } 116 | var parameters = DataHelper.GetParams(this.EbConnectionFactory.ObjectsDB, _isPaged, request.Params, request.Length, request.Start); 117 | Console.WriteLine("Before : " + DateTime.Now); 118 | var dtStart = DateTime.Now; 119 | Console.WriteLine("................................................datasourceDSrequeststart " + DateTime.Now); 120 | var _dataset = this.EbConnectionFactory.ObjectsDB.DoQueries(_sql, parameters.ToArray()); 121 | Console.WriteLine("................................................datasourceDSrequeststart " + DateTime.Now); 122 | var dtstop = DateTime.Now; 123 | Console.WriteLine("..................................totaltimeinSeconds" + dtstop.Subtract(dtStart).Seconds); 124 | 125 | //-- 126 | Console.WriteLine(DateTime.Now); 127 | var dtEnd = DateTime.Now; 128 | var ts = (dtEnd - dtStart).TotalMilliseconds; 129 | Console.WriteLine("final:::" + ts); 130 | int _recordsTotal = 0, _recordsFiltered = 0; 131 | if (_isPaged) 132 | { 133 | Int32.TryParse(_dataset.Tables[0].Rows[0][0].ToString(), out _recordsTotal); 134 | Int32.TryParse(_dataset.Tables[0].Rows[0][0].ToString(), out _recordsFiltered); 135 | } 136 | _recordsTotal = (_recordsTotal > 0) ? _recordsTotal : _dataset.Tables[0].Rows.Count; 137 | _recordsFiltered = (_recordsFiltered > 0) ? _recordsFiltered : _dataset.Tables[0].Rows.Count; 138 | //-- 139 | 140 | dsresponse = new FDDataResponse 141 | { 142 | Draw = request.Draw, 143 | Data = (_dataset.Tables.Count > 1) ? _dataset.Tables[1].Rows : _dataset.Tables[0].Rows, 144 | RecordsTotal = _recordsTotal, 145 | RecordsFiltered = _recordsFiltered, 146 | Ispaged = _isPaged 147 | }; 148 | this.Log.Info("dsresponse*****" + dsresponse.Data); 149 | var x = EbSerializers.Json_Serialize(dsresponse); 150 | return dsresponse; 151 | } 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /Services/GoogleMapServices.cs: -------------------------------------------------------------------------------- 1 | using ExpressBase.Common; 2 | using ExpressBase.Common.Data; 3 | using ExpressBase.Objects.ServiceStack_Artifacts; 4 | using ServiceStack; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Threading.Tasks; 9 | 10 | namespace ExpressBase.ServiceStack 11 | { 12 | [ClientCanSwapTemplates] 13 | [Authenticate] 14 | public class GoogleMapServices : EbBaseService 15 | { 16 | public GoogleMapServices(IEbConnectionFactory _dbf) : base(_dbf) { } 17 | 18 | public GoogleMapResponse Any(GoogleMapRequest request) 19 | { 20 | List f = new List(); 21 | var _sql = "select * from eb_google_map;"; 22 | var dt = this.EbConnectionFactory.ObjectsDB.DoQuery(_sql); 23 | foreach (EbDataRow dr in dt.Rows) 24 | { 25 | var _ebObject = (new EbGoogleData 26 | { 27 | lat = dr[1].ToString(), 28 | lon = dr[2].ToString(), 29 | name = dr[3].ToString() 30 | }); 31 | f.Add(_ebObject); 32 | } 33 | return new GoogleMapResponse { Data = f }; 34 | } 35 | } 36 | } 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /Services/IoTService.cs: -------------------------------------------------------------------------------- 1 | using ExpressBase.Objects.ServiceStack_Artifacts; 2 | using ServiceStack; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Data.Common; 6 | using System.Linq; 7 | using System.Threading.Tasks; 8 | 9 | namespace ExpressBase.ServiceStack.Services 10 | { 11 | [Authenticate] 12 | public class IoTService : EbBaseService 13 | { 14 | public object Any(IoTDataRequest request) 15 | { 16 | request.SolnId = "ebdblvnzp5spac20200127092930"; 17 | string _sql = "INSERT INTO ronds_sample(json) values(:json);"; 18 | try 19 | { 20 | this.EbConnectionFactory = new Common.Data.EbConnectionFactory(request.SolnId, this.Redis); 21 | DbParameter[] parameters = new DbParameter[] { this.EbConnectionFactory.DataDB.GetNewParameter("json", Common.Structures.EbDbTypes.String, request.Data) }; 22 | int result = this.EbConnectionFactory.ObjectsDB.DoNonQuery(_sql, parameters); 23 | } 24 | catch (Exception e) 25 | { 26 | Console.WriteLine("IoT -----------------" + e.Message + "Stacktrace:----------" + e.StackTrace); 27 | } 28 | return new IoTDataResponse(); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Services/MenuServices.cs: -------------------------------------------------------------------------------- 1 | using ExpressBase.Common; 2 | using ExpressBase.Common.Data; 3 | using ExpressBase.Common.Objects; 4 | using ExpressBase.Common.Structures; 5 | using ExpressBase.Objects.ServiceStack_Artifacts; 6 | using System; 7 | using System.Collections.Generic; 8 | using System.Data.Common; 9 | using System.Linq; 10 | using System.Runtime.Serialization; 11 | using System.Threading.Tasks; 12 | using ExpressBase.Security; 13 | using ExpressBase.Common.Constants; 14 | using ServiceStack; 15 | 16 | namespace ExpressBase.ServiceStack.Services 17 | { 18 | [Authenticate] 19 | public class MenuServices : EbBaseService 20 | { 21 | public MenuServices(IEbConnectionFactory _dbf) : base(_dbf) { } 22 | 23 | public User UserObject { set; get; } 24 | 25 | private List GetAccessIds(int lid) 26 | { 27 | List ObjIds = new List(); 28 | foreach (string perm in this.UserObject.Permissions) 29 | { 30 | int id = Convert.ToInt32(perm.Split(CharConstants.DASH)[2]); 31 | int locid = Convert.ToInt32(perm.Split(CharConstants.COLON)[1]); 32 | if ((lid == locid || locid == -1) && !ObjIds.Contains(id.ToString())) 33 | ObjIds.Add(id.ToString()); 34 | } 35 | return ObjIds; 36 | } 37 | 38 | public SidebarUserResponse Get(SidebarUserRequest request) 39 | { 40 | EbDataSet ds = new EbDataSet(); 41 | Dictionary appColl = new Dictionary(); 42 | List _fav = new List(); 43 | List _favids = new List(); 44 | 45 | this.UserObject = GetUserObject(request.UserAuthId); 46 | 47 | DbParameter[] parameters = { 48 | this.EbConnectionFactory.ObjectsDB.GetNewParameter("user_id",EbDbTypes.Int32,request.UserId) 49 | }; 50 | 51 | if (this.UserObject.Roles.Contains("SolutionOwner") || this.UserObject.Roles.Contains("SolutionAdmin")) 52 | { 53 | if (EbConnectionFactory.ObjectsDB.Vendor == DatabaseVendors.MYSQL) 54 | { 55 | ds = this.EbConnectionFactory.ObjectsDB.DoQueries((this.EbConnectionFactory.ObjectsDB as MySqlDB).EB_SIDEBARUSER_REQUEST_SOL_OWNER, parameters); 56 | } 57 | else 58 | { 59 | ds = this.EbConnectionFactory.ObjectsDB.DoQueries(this.EbConnectionFactory.ObjectsDB.EB_SIDEBARUSER_REQUEST.Replace(this.EbConnectionFactory.ObjectsDB.EB_SIDEBARCHECK, string.Empty), parameters); 60 | } 61 | } 62 | else 63 | { 64 | string Ids = String.Join(",", this.GetAccessIds(request.LocationId)); 65 | 66 | ds = this.EbConnectionFactory.ObjectsDB.DoQueries(this.EbConnectionFactory.ObjectsDB.EB_SIDEBARUSER_REQUEST.Replace(":Ids", string.IsNullOrEmpty(Ids) ? "0" : Ids), parameters); 67 | } 68 | 69 | foreach (EbDataRow row in ds.Tables[2].Rows) 70 | { 71 | _favids.Add(Convert.ToInt32(row[0])); 72 | } 73 | 74 | foreach (EbDataRow dr in ds.Tables[0].Rows) 75 | { 76 | var id = Convert.ToInt32(dr[0]); 77 | if (!appColl.Keys.Contains(id)) 78 | appColl.Add(id, new AppObject { AppName = dr[1].ToString(), AppIcon = dr[2].ToString() }); 79 | } 80 | 81 | Dictionary _Coll = new Dictionary(); 82 | foreach (EbDataRow dr in ds.Tables[1].Rows) 83 | { 84 | int appid = Convert.ToInt32(dr["app_id"]); 85 | 86 | if (!_Coll.Keys.Contains(appid)) 87 | _Coll.Add(appid, new AppWrap { Types = new Dictionary() }); 88 | 89 | Dictionary _types = new Dictionary(); 90 | int typeId = Convert.ToInt32(dr["obj_type"]); 91 | EbObjectType ___otyp = (EbObjectType)Convert.ToInt32(typeId); 92 | 93 | if (___otyp.IsUserFacing) 94 | { 95 | if (!_Coll[appid].Types.Keys.Contains(typeId)) 96 | _Coll[appid].Types.Add(typeId, new TypeWrap { Objects = new List() }); 97 | 98 | ObjWrap owrap = new ObjWrap 99 | { 100 | Id = Convert.ToInt32(dr["objectid"]), 101 | EbObjectType = typeId, 102 | Refid = dr["refid"].ToString(), 103 | AppId = appid, 104 | EbType = ___otyp.Name, 105 | DisplayName = dr["display_name"].ToString() 106 | }; 107 | 108 | _Coll[appid].Types[typeId].Objects.Add(owrap); 109 | 110 | if (_favids.Contains(owrap.Id)) 111 | { 112 | owrap.Favourite = true; 113 | _fav.Add(owrap); 114 | } 115 | } 116 | } 117 | return new SidebarUserResponse { Data = _Coll, AppList = appColl, Favourites = _fav }; 118 | } 119 | 120 | public SidebarDevResponse Get(SidebarDevRequest request) 121 | { 122 | string sql = @"SELECT id, applicationname,app_icon FROM eb_applications 123 | WHERE COALESCE(eb_del, 'F') = 'F' ORDER BY applicationname; 124 | SELECT 125 | EO.id, EO.obj_type, EO.obj_name, EO.obj_desc, COALESCE(EO2A.app_id, 0),display_name 126 | FROM 127 | eb_objects EO 128 | LEFT JOIN 129 | eb_objects2application EO2A 130 | ON 131 | EO.id = EO2A.obj_id 132 | WHERE 133 | COALESCE(EO2A.eb_del, 'F') = 'F' 134 | AND COALESCE( EO.eb_del, 'F') = 'F' 135 | ORDER BY 136 | EO.obj_type;"; 137 | var ds = this.EbConnectionFactory.ObjectsDB.DoQueries(sql); 138 | 139 | Dictionary appColl = new Dictionary(); 140 | 141 | foreach (EbDataRow dr in ds.Tables[0].Rows) 142 | { 143 | var id = Convert.ToInt32(dr[0]); 144 | if (!appColl.Keys.Contains(id)) 145 | appColl.Add(id, new AppObject { AppName = dr[1].ToString(), AppIcon = dr[2].ToString() }); 146 | } 147 | 148 | Dictionary _Coll = new Dictionary(); 149 | try 150 | { 151 | foreach (EbDataRow dr in ds.Tables[1].Rows) 152 | { 153 | var appid = Convert.ToInt32(dr[4]); 154 | 155 | if (!_Coll.Keys.Contains(appid)) 156 | _Coll.Add(appid, new AppWrap { Types = new Dictionary() }); 157 | 158 | Dictionary _types = new Dictionary(); 159 | var typeId = Convert.ToInt32(dr[1]); 160 | 161 | if (!_Coll[appid].Types.Keys.Contains(typeId)) 162 | _Coll[appid].Types.Add(typeId, new TypeWrap { Objects = new List() }); 163 | 164 | var ___otyp = (EbObjectType)Convert.ToInt32(dr[1]); 165 | _Coll[appid].Types[typeId].Objects.Add(new ObjWrap 166 | { 167 | Id = (dr[0] != null) ? Convert.ToInt32(dr[0]) : 0, 168 | EbObjectType = (dr[1] != null) ? Convert.ToInt32(dr[1]) : 0, 169 | EbType = ___otyp.ToString(), 170 | AppId = (Convert.ToInt32(dr[4]) == 0) ? 0 : Convert.ToInt32(dr[4]), 171 | DisplayName = dr[5].ToString(), 172 | }); 173 | } 174 | 175 | } 176 | catch (Exception ee) 177 | { 178 | Console.BackgroundColor = ConsoleColor.Red; 179 | Console.WriteLine("Exception:" + ee.Message); 180 | Console.BackgroundColor = ConsoleColor.White; 181 | } 182 | 183 | return new SidebarDevResponse { Data = _Coll, AppList = appColl }; 184 | } 185 | 186 | 187 | public AddFavouriteResponse Post(AddFavouriteRequest request) 188 | { 189 | AddFavouriteResponse resp = new AddFavouriteResponse(); 190 | try 191 | { 192 | string sql =EbConnectionFactory.ObjectsDB.EB_ADD_FAVOURITE; 193 | DbParameter[] parameter = 194 | { 195 | this.EbConnectionFactory.ObjectsDB.GetNewParameter("userid",EbDbTypes.Int32,request.UserId), 196 | this.EbConnectionFactory.ObjectsDB.GetNewParameter("objectid",EbDbTypes.Int32,request.ObjId) 197 | }; 198 | 199 | int rows_affected = this.EbConnectionFactory.ObjectsDB.DoNonQuery(sql, parameter); 200 | 201 | if (rows_affected > 0) 202 | resp.Status = true; 203 | else 204 | resp.Status = false; 205 | } 206 | catch(Exception e) 207 | { 208 | Console.WriteLine("Exception at Adding to Fav: " + e.Message); 209 | resp.Status = false; 210 | } 211 | return resp; 212 | } 213 | 214 | public RemoveFavouriteResponse Post(RemoveFavouriteRequest request) 215 | { 216 | RemoveFavouriteResponse resp = new RemoveFavouriteResponse(); 217 | try 218 | { 219 | string sql = EbConnectionFactory.ObjectsDB.EB_REMOVE_FAVOURITE; 220 | 221 | DbParameter[] parameter = { 222 | this.EbConnectionFactory.ObjectsDB.GetNewParameter("userid",EbDbTypes.Int32,request.UserId), 223 | this.EbConnectionFactory.ObjectsDB.GetNewParameter("objectid",EbDbTypes.Int32,request.ObjId) 224 | }; 225 | 226 | int rows_affected = this.EbConnectionFactory.ObjectsDB.DoNonQuery(sql, parameter); 227 | 228 | if (rows_affected > 0) 229 | resp.Status = true; 230 | else 231 | resp.Status = false; 232 | } 233 | catch (Exception e) 234 | { 235 | Console.WriteLine("Exception at Remove From Fav: " + e.Message); 236 | resp.Status = false; 237 | } 238 | return resp; 239 | } 240 | } 241 | } 242 | -------------------------------------------------------------------------------- /Services/MultiLanguageService.cs: -------------------------------------------------------------------------------- 1 | using ExpressBase.Common; 2 | using ExpressBase.Common.Data; 3 | using ExpressBase.Common.Structures; 4 | using ExpressBase.Objects.ServiceStack_Artifacts; 5 | using ServiceStack; 6 | using System; 7 | using System.Collections.Generic; 8 | using System.Data.Common; 9 | using System.Linq; 10 | using System.Text; 11 | 12 | namespace ExpressBase.ServiceStack.Services 13 | { 14 | [ClientCanSwapTemplates] 15 | //[DefaultView("Form")] 16 | [Authenticate] 17 | 18 | public class MultiLanguageService : EbBaseService 19 | { 20 | public MultiLanguageService(IEbConnectionFactory _dbf) : base(_dbf) { } 21 | 22 | 23 | //------------------------------------------------------------------------------------------------------------- 24 | 25 | //string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Febin\Downloads\Word-lists-in-csv\Word lists in csv\Aword.csv"); 26 | //StringBuilder query2 = new StringBuilder(); 27 | //query2.Append(@"insert into eb_keys (key) values"); 28 | //int j = 0; 29 | //for (int i = 1; i < lines.Length; i++) 30 | //{ 31 | // if (lines[i - 1] != lines[i]) 32 | // { 33 | // query2.Append("('"+ lines[i].Trim() + "'),"); 34 | // j++; 35 | // } 36 | // if (j / 100 == 1) 37 | // { 38 | // j = 0; 39 | // query2.Length = query2.Length - 1; 40 | // query2.Append(";"); 41 | // List parameters1 = new List(); 42 | // var dt1 = this.TenantDbFactory.ObjectsDB.DoNonQuery(query2.ToString(), parameters1.ToArray()); 43 | // query2.Clear(); 44 | // query2.Append(@"insert into eb_keys (key) values"); 45 | // Console.WriteLine("ok ", +i); 46 | // } 47 | //} 48 | 49 | //string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Febin\Downloads\Word-lists-in-csv\Word lists in csv\Aword.csv"); 50 | //StringBuilder query2 = new StringBuilder(); 51 | //query2.Append(@"insert into eb_keyvalue (key_id,lang_id,value) values"); 52 | //int kidstart = 33; 53 | //int[] lid = { 1,2,6,7,8,9,10,11,12,13}; 54 | //string[] lnotation = {"ch","sp","hi","en","po","ar","ru","be","pu","ja" }; 55 | 56 | //int j = 0; 57 | //for (int i=1;i< lines.Length; i++) 58 | //{ 59 | // if (lines[i - 1] != lines[i]) 60 | // { 61 | // for(int k = 0; k < 10; k++) 62 | // query2.Append("(" + kidstart + "," + lid[k] + ",'" + lnotation[k] +lines[i] + "'),"); 63 | // j++; 64 | // kidstart++; 65 | // } 66 | // if (j / 100 == 1) 67 | // { 68 | // j = 0; 69 | // query2.Length = query2.Length - 1; 70 | // query2.Append(";"); 71 | // List parameters1 = new List(); 72 | // var dt1 = this.TenantDbFactory.ObjectsDB.DoNonQuery(query2.ToString(), parameters1.ToArray()); 73 | // query2.Clear(); 74 | // query2.Append(@"insert into eb_keyvalue (key_id,lang_id,value) values"); 75 | // Console.WriteLine("ok "+i); 76 | // } 77 | //} 78 | 79 | 80 | //------------------------------------------------------------------------------------------------------------- 81 | 82 | 83 | public object Get(MLGetSearchResultRqst request) 84 | { 85 | Dictionary> dict = new Dictionary>(); 86 | string query = string.Format(EbConnectionFactory.ObjectsDB.EB_GET_MLSEARCHRESULT); 87 | List parameters = new List(); 88 | parameters.Add(this.EbConnectionFactory.ObjectsDB.GetNewParameter("KEY", EbDbTypes.String, (request.Key_String + "%"))); 89 | parameters.Add(this.EbConnectionFactory.ObjectsDB.GetNewParameter("OFFSET", EbDbTypes.Int32, request.Offset)); 90 | parameters.Add(this.EbConnectionFactory.ObjectsDB.GetNewParameter("LIMIT", EbDbTypes.Int32, request.Limit)); 91 | var ds = this.EbConnectionFactory.ObjectsDB.DoQueries(query, parameters.ToArray()); 92 | int i = -1; 93 | Dictionary map = new Dictionary(); 94 | var count = ds.Tables[0].Rows[0][0]; 95 | foreach (EbDataRow dr in ds.Tables[1].Rows) 96 | { 97 | long k = Convert.ToInt64(dr[0]); 98 | if (!map.ContainsKey(k)) 99 | { 100 | map.Add(k, ++i); 101 | dict.Add(i, new List()); 102 | } 103 | dict[map[k]].Add(new MLSearchResult { KeyId = Convert.ToInt64(dr[0]), Key = dr[1].ToString(), LangId = Convert.ToInt32(dr[2]), Language = dr[3].ToString(), KeyValId = Convert.ToInt64(dr[4]), KeyValue = dr[5].ToString() }); 104 | } 105 | return new MLGetSearchResultRspns { D_member = dict, Count = Convert.ToInt32(count) }; 106 | } 107 | 108 | public object Get(MLLoadLangRequest request) 109 | { 110 | string query = string.Format(@"SELECT id,name FROM eb_languages ORDER BY name ASC"); 111 | List parameters = new List(); 112 | var dt = this.EbConnectionFactory.ObjectsDB.DoQuery(query, parameters.ToArray()); 113 | Dictionary dict = new Dictionary(); 114 | foreach (EbDataRow dr in dt.Rows) 115 | dict.Add(dr[1].ToString(), Convert.ToInt32(dr[0])); 116 | return new MLLoadLangResponse { Data = dict }; 117 | } 118 | 119 | public object Get(MLGetStoredKeyValueRequest request) 120 | { 121 | Dictionary dict = new Dictionary(); 122 | string query = string.Format(@"SELECT C.id, A.key, A.id, B.id, C.value 123 | FROM eb_keys A, eb_languages B, eb_keyvalue C 124 | WHERE A.id=C.key_id AND B.id=C.lang_id AND LOWER(A.key) LIKE LOWER(@KEY) 125 | ORDER BY B.name ASC"); 126 | List parameters = new List(); 127 | parameters.Add(this.EbConnectionFactory.ObjectsDB.GetNewParameter("KEY", EbDbTypes.String, request.Key)); 128 | var dt = this.EbConnectionFactory.ObjectsDB.DoQuery(query, parameters.ToArray()); 129 | int i = 0; 130 | foreach (EbDataRow dr in dt.Rows) 131 | dict.Add(i++, new MLKeyValue { KeyVal_Id = dr[0].ToString(), Key = dr[1].ToString(), Key_Id = dr[2].ToString(), Lang_Id = dr[3].ToString(), KeyVal_Value = dr[4].ToString() }); 132 | return new MLGetStoredKeyValueResponse { Data = dict }; 133 | } 134 | 135 | public object Get(MLUpdateKeyValueRequest request) 136 | { 137 | List list = request.Data; 138 | if (list.Count() == 0) 139 | return null; 140 | int InsertCount = 0; 141 | StringBuilder query1 = new StringBuilder(); 142 | query1.Append(@"INSERT INTO eb_keyvalue (key_id,lang_id,value) VALUES"); 143 | List parameters1 = new List(); 144 | string lid = "@LANG_ID", kval = "@KEY_VALUE", kid = "@KEY_ID"; 145 | int rcount = 0; 146 | for (int i = 0; i < list.Count(); i++) 147 | if (list[i].KeyVal_Id == "") 148 | { 149 | query1.Append("( " + (kid + rcount) + "," + (lid + rcount) + "," + (kval + rcount) + "),"); 150 | parameters1.Add(this.EbConnectionFactory.ObjectsDB.GetNewParameter((kid + rcount), EbDbTypes.Int64, list[i].Key_Id)); 151 | parameters1.Add(this.EbConnectionFactory.ObjectsDB.GetNewParameter((lid + rcount), EbDbTypes.Int32, list[i].Lang_Id)); 152 | parameters1.Add(this.EbConnectionFactory.ObjectsDB.GetNewParameter((kval + rcount), EbDbTypes.String, list[i].KeyVal_Value)); 153 | rcount++; 154 | list.Remove(list[i]); 155 | i--; 156 | InsertCount++; 157 | } 158 | query1.Length = query1.Length - 1; 159 | query1.Append(";"); 160 | int dt1 = 0; 161 | if (InsertCount > 0) 162 | dt1 = this.EbConnectionFactory.ObjectsDB.DoNonQuery(query1.ToString(), parameters1.ToArray()); 163 | if (list.Count() == 0) 164 | return new MLUpdateKeyValueResponse { Data = dt1 }; 165 | StringBuilder sb = new StringBuilder(); 166 | List parameters2 = new List(); 167 | rcount = 0; 168 | foreach (MLKeyValue obj in list) 169 | { 170 | string t = string.Format("UPDATE eb_keyvalue SET value=@{0} WHERE id=@{1};", "keyvalvalue_" + rcount, "keyvalid_" + rcount); 171 | sb.Append(t); 172 | parameters2.Add(this.EbConnectionFactory.ObjectsDB.GetNewParameter("keyvalid_" + rcount, EbDbTypes.Int64, obj.KeyVal_Id)); 173 | parameters2.Add(this.EbConnectionFactory.ObjectsDB.GetNewParameter("keyvalvalue_" + rcount, EbDbTypes.String, obj.KeyVal_Value)); 174 | rcount++; 175 | } 176 | var dt2 = this.EbConnectionFactory.ObjectsDB.DoNonQuery(sb.ToString(), parameters2.ToArray()); 177 | return new MLUpdateKeyValueResponse { Data = dt1 + dt2 }; 178 | } 179 | 180 | public object Get(MLAddKeyRequest request) 181 | { 182 | List list = request.Data; 183 | 184 | string query1 = EbConnectionFactory.ObjectsDB.EB_MLADDKEY; 185 | using (var con = this.EbConnectionFactory.ObjectsDB.GetNewConnection()) 186 | { 187 | con.Open(); 188 | using (DbCommand cmd = this.EbConnectionFactory.ObjectsDB.GetNewCommand(con, query1)) 189 | { 190 | cmd.Parameters.Add(this.EbConnectionFactory.ObjectsDB.GetNewParameter("KEY", EbDbTypes.String, request.Key)); 191 | var key_id = cmd.ExecuteScalar().ToString(); 192 | 193 | StringBuilder query2 = new StringBuilder(); 194 | query2.Append(@"INSERT INTO eb_keyvalue (key_id,lang_id,value) VALUES"); 195 | string kid = "@KEY_ID", lid = "@LANG_ID", kval = "@KEY_VALUE"; 196 | int i = 0; 197 | List parameters = new List(); 198 | foreach (MLAddKey obj in request.Data) 199 | { 200 | query2.Append("(" + (kid + i) + "," + (lid + i) + "," + (kval + i) + "),"); 201 | parameters.Add(this.EbConnectionFactory.ObjectsDB.GetNewParameter((kid + i), EbDbTypes.Int64, key_id)); 202 | parameters.Add(this.EbConnectionFactory.ObjectsDB.GetNewParameter((lid + i), EbDbTypes.Int32, obj.Lang_Id)); 203 | parameters.Add(this.EbConnectionFactory.ObjectsDB.GetNewParameter((kval + i), EbDbTypes.String, obj.Key_Value)); 204 | i++; 205 | } 206 | query2.Length = query2.Length - 1; 207 | query2.Append(";"); 208 | var dt = this.EbConnectionFactory.ObjectsDB.DoNonQuery(query2.ToString(), parameters.ToArray()); 209 | return new MLAddKeyResponse { KeyId = Convert.ToInt32(key_id), RowAffected = dt }; 210 | } 211 | } 212 | } 213 | } 214 | } 215 | -------------------------------------------------------------------------------- /Services/ProfilerServices.cs: -------------------------------------------------------------------------------- 1 | using ExpressBase.Common; 2 | using ExpressBase.Common.Data; 3 | using ExpressBase.Common.Structures; 4 | using ExpressBase.Objects.ServiceStack_Artifacts; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Data.Common; 8 | using System.Linq; 9 | using System.Threading.Tasks; 10 | using ExpressBase.Common.SqlProfiler; 11 | using Newtonsoft.Json; 12 | using ServiceStack; 13 | 14 | namespace ExpressBase.ServiceStack.Services 15 | { 16 | [Authenticate] 17 | public class ProfilerServices : EbBaseService 18 | { 19 | public ProfilerServices(IEbConnectionFactory _dbf) : base(_dbf) { } 20 | 21 | public ProfilerQueryResponse Get(ProfilerQueryColumnRequest request) 22 | { 23 | List _logs = new List(); 24 | List parameters = new List(); 25 | string query = EbConnectionFactory.ObjectsDB.EB_PROFILER_QUERY_COLUMN; 26 | parameters.Add(EbConnectionFactory.ObjectsDB.GetNewParameter("refid", EbDbTypes.String, request.RefId)); 27 | var _dt = EbConnectionFactory.ObjectsDB.DoQuery(query, parameters.ToArray()); 28 | return new ProfilerQueryResponse { ColumnCollection = _dt.Columns, data = _dt.Rows }; 29 | } 30 | 31 | public ProfilerQueryResponse Get(ProfilerQueryDataRequest request) 32 | { 33 | List parameters = new List(); 34 | string query = EbConnectionFactory.ObjectsDB.EB_PROFILER_QUERY_DATA; 35 | parameters.Add(EbConnectionFactory.ObjectsDB.GetNewParameter("refid", EbDbTypes.String, request.RefId)); 36 | parameters.Add(EbConnectionFactory.ObjectsDB.GetNewParameter("limit", EbDbTypes.Int32, request.Length)); 37 | parameters.Add(EbConnectionFactory.ObjectsDB.GetNewParameter("offset", EbDbTypes.Int32, request.Start)); 38 | var _ds = EbConnectionFactory.ObjectsDB.DoQueries(query, parameters.ToArray()); 39 | return new ProfilerQueryResponse { Draw = request.Draw, data = _ds.Tables[1].Rows, RecordsTotal = Convert.ToInt32(_ds.Tables[0].Rows[0][0]), RecordsFiltered = Convert.ToInt32(_ds.Tables[0].Rows[0][0]) }; 40 | } 41 | 42 | public GetProfilersResponse Get(GetProfilersRequest request) 43 | { 44 | List _logs = new List(); 45 | List parameters = new List(); 46 | Profiler profiler = new Profiler(); 47 | string query = EbConnectionFactory.ObjectsDB.EB_GET_PROFILERS; 48 | parameters.Add(EbConnectionFactory.ObjectsDB.GetNewParameter("refid", EbDbTypes.String, request.RefId)); 49 | EbDataSet dt = EbConnectionFactory.ObjectsDB.DoQueries(query, parameters.ToArray()); 50 | if (dt.Tables.Count > 0) 51 | { 52 | profiler.Max_id = (dt.Tables[0].Rows.Count != 0) ? Convert.ToInt32(dt.Tables[0].Rows[0][0]) : 0; 53 | profiler.Max_exectime = (dt.Tables[0].Rows.Count != 0) ? Convert.ToDecimal(dt.Tables[0].Rows[0][1]) : Convert.ToDecimal(0); 54 | profiler.Min_id = (dt.Tables[1].Rows.Count != 0) ? Convert.ToInt32(dt.Tables[1].Rows[0][0]) : 0; 55 | profiler.Min_exectime = (dt.Tables[1].Rows.Count != 0) ? Convert.ToDecimal(dt.Tables[1].Rows[0][1]) : Convert.ToDecimal(0); 56 | profiler.Cur_Mon_Max_id = (dt.Tables[2].Rows.Count != 0) ? Convert.ToInt32(dt.Tables[2].Rows[0][0]) : 0; 57 | profiler.Cur_Mon_Max_exectime = (dt.Tables[2].Rows.Count != 0) ? Convert.ToDecimal(dt.Tables[2].Rows[0][1]) : Convert.ToDecimal(0); 58 | profiler.Cur_Mon_Min_id = (dt.Tables[3].Rows.Count != 0) ? Convert.ToInt32(dt.Tables[3].Rows[0][0]) : 0; 59 | profiler.Cur_Mon_Min_exectime = (dt.Tables[3].Rows.Count != 0) ? Convert.ToDecimal(dt.Tables[3].Rows[0][1]) : Convert.ToDecimal(0); 60 | profiler.Cur_Max_id = (dt.Tables[4].Rows.Count != 0) ? Convert.ToInt32(dt.Tables[4].Rows[0][0]) : 0; 61 | profiler.Cur_Max_exectime = (dt.Tables[4].Rows.Count != 0) ? Convert.ToDecimal(dt.Tables[4].Rows[0][1]) : Convert.ToDecimal(0); 62 | profiler.Cur_Min_id = (dt.Tables[5].Rows.Count != 0) ? Convert.ToInt32(dt.Tables[5].Rows[0][0]) : 0; 63 | profiler.Cur_Min_exectime = (dt.Tables[5].Rows.Count != 0) ? Convert.ToDecimal(dt.Tables[5].Rows[0][1]) : Convert.ToDecimal(0); 64 | profiler.Total_count = (dt.Tables[6].Rows.Count != 0) ? Convert.ToInt32(dt.Tables[6].Rows[0][0]) : 0; 65 | profiler.Current_count = (dt.Tables[7].Rows.Count != 0) ? Convert.ToInt32(dt.Tables[7].Rows[0][0]) : 0; 66 | profiler.Month_count = (dt.Tables[8].Rows.Count != 0) ? Convert.ToInt32(dt.Tables[8].Rows[0][0]) : 0; 67 | } 68 | return new GetProfilersResponse { Profiler = profiler }; 69 | } 70 | 71 | public GetLogdetailsResponse Get(GetLogdetailsRequest request) 72 | { 73 | string sql = "SELECT * FROM eb_executionlogs WHERE id = @id"; 74 | DbParameter[] p = { EbConnectionFactory.ObjectsDB.GetNewParameter("id", EbDbTypes.Int32, request.Index) }; 75 | EbDataTable _logdetails = EbConnectionFactory.ObjectsDB.DoQuery(sql, p); 76 | 77 | EbExecutionLogs logs = null; 78 | if (_logdetails.Rows.Count > 0) 79 | logs = new EbExecutionLogs { Rows = _logdetails.Rows[0][1].ToString(), Exec_time = Convert.ToInt32(_logdetails.Rows[0][2]), Username = _logdetails.Rows[0][3].ToString(), Created_at = Convert.ToDateTime(_logdetails.Rows[0][4]), Params = JsonConvert.DeserializeObject>(_logdetails.Rows[0][6].ToString()) }; 80 | return new GetLogdetailsResponse { logdetails = logs }; 81 | } 82 | 83 | public GetChartDetailsResponse Get(GetChartDetailsRequest request) 84 | { 85 | string sql = EbConnectionFactory.ObjectsDB.EB_GET_CHART_DETAILS; 86 | DbParameter[] p = { EbConnectionFactory.ObjectsDB.GetNewParameter("refid", EbDbTypes.String, request.Refid) }; 87 | EbDataTable _chartdetails = EbConnectionFactory.ObjectsDB.DoQuery(sql, p); 88 | return new GetChartDetailsResponse { data = _chartdetails.Rows }; 89 | } 90 | 91 | public GetChart2DetailsResponse Get(GetChart2DetailsRequest request) 92 | { 93 | string sql = EbConnectionFactory.ObjectsDB.EB_GET_CHART_2_DETAILS; 94 | DbParameter[] p = { EbConnectionFactory.ObjectsDB.GetNewParameter("refid", EbDbTypes.String, request.Refid) }; 95 | EbDataTable _chartdetails = EbConnectionFactory.ObjectsDB.DoQuery(sql, p); 96 | return new GetChart2DetailsResponse { data = _chartdetails.Rows }; 97 | } 98 | 99 | public GetExplainResponse Get(GetExplainRequest request) 100 | { 101 | string query = request.Query.Split(";")[0]; 102 | string sql=""; 103 | if (EbConnectionFactory.ObjectsDB.Vendor == DatabaseVendors.PGSQL) 104 | { 105 | sql = "explain (format json, analyze on) " + query + ";"; 106 | } 107 | else if (EbConnectionFactory.ObjectsDB.Vendor == DatabaseVendors.MYSQL) 108 | { 109 | sql = " EXPLAIN FORMAT=JSON " + query + ";"; 110 | } 111 | var parameters = DataHelper.GetParams(this.EbConnectionFactory.ObjectsDB, false, request.Params, 0, 0); 112 | EbDataTable _explain = EbConnectionFactory.ObjectsDB.DoQuery(sql, parameters.ToArray()); 113 | 114 | Dictionary _d = new Dictionary(); 115 | if (EbConnectionFactory.ObjectsDB.Vendor == DatabaseVendors.PGSQL) 116 | { 117 | _d.Add("vendor", DatabaseVendors.PGSQL.ToString()); 118 | } 119 | else if (EbConnectionFactory.ObjectsDB.Vendor == DatabaseVendors.MYSQL) 120 | { 121 | _d.Add("vendor", DatabaseVendors.MYSQL.ToString()); 122 | } 123 | _d.Add("json", _explain.Rows[0][0].ToString()); 124 | 125 | return new GetExplainResponse { Explain = JsonConvert.SerializeObject(_d)}; 126 | } 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /Services/RedisClientServices.cs: -------------------------------------------------------------------------------- 1 | using ExpressBase.Common.Data; 2 | using ExpressBase.Common.Structures; 3 | using ExpressBase.Objects.ServiceStack_Artifacts; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Data.Common; 7 | using System.Linq; 8 | using System.Threading.Tasks; 9 | using ExpressBase.Common; 10 | using ServiceStack; 11 | 12 | namespace ExpressBase.ServiceStack.Services 13 | { 14 | [Authenticate] 15 | public class RedisClientServices : EbBaseService 16 | { 17 | public RedisClientServices(IEbConnectionFactory _dbf) : base(_dbf) { } 18 | 19 | public LogRedisInsertResponse Post(LogRedisInsertRequest request) 20 | { 21 | string query = @"INSERT INTO eb_redis_logs (changed_by, operation, changed_at, prev_value, new_value, soln_id, key) VALUES(:usr, :opn, NOW(), :prev, :new, 22 | :sln, :key);"; 23 | DbParameter[] parameters = { 24 | InfraConnectionFactory.ObjectsDB.GetNewParameter("usr", EbDbTypes.Int32, request.UserId), 25 | InfraConnectionFactory.ObjectsDB.GetNewParameter("opn", EbDbTypes.Int32, request.Operation), 26 | InfraConnectionFactory.ObjectsDB.GetNewParameter("prev", EbDbTypes.String, request.PreviousValue), 27 | InfraConnectionFactory.ObjectsDB.GetNewParameter("new", EbDbTypes.String, request.NewValue), 28 | InfraConnectionFactory.ObjectsDB.GetNewParameter("sln", EbDbTypes.Int32, request.SolutionId), 29 | InfraConnectionFactory.ObjectsDB.GetNewParameter("key", EbDbTypes.String, request.Key) 30 | }; 31 | this.InfraConnectionFactory.ObjectsDB.DoNonQuery(query, parameters); 32 | return new LogRedisInsertResponse(); 33 | } 34 | 35 | public LogRedisGetResponse Get(LogRedisGetRequest request) 36 | { 37 | List r_logs = new List(); 38 | List parameters = new List(); 39 | string query = @"SELECT changed_by, operation, changed_at, soln_id, key, id FROM eb_redis_logs WHERE soln_id = :slnid order by changed_at desc"; 40 | parameters.Add(InfraConnectionFactory.ObjectsDB.GetNewParameter("slnid", EbDbTypes.Int32, request.SolutionId)); 41 | EbDataTable dt = InfraConnectionFactory.ObjectsDB.DoQuery(query, parameters.ToArray()); 42 | foreach (var item in dt.Rows) 43 | { 44 | EbRedisLogs eb = new EbRedisLogs 45 | { 46 | LogId = Convert.ToInt32(item[5]), 47 | ChangedBy = Convert.ToInt32(item[0]), 48 | ChangedAt = Convert.ToDateTime(item[2]), 49 | Operation = Enum.GetName(typeof(RedisOperations), item[1]), 50 | Key = (item[4]).ToString() 51 | }; 52 | r_logs.Add(eb); 53 | } 54 | return new LogRedisGetResponse { Logs = r_logs }; 55 | } 56 | 57 | public LogRedisViewChangesResponse Get(LogRedisViewChangesRequest request) 58 | { 59 | 60 | //EbRedisLogValues ebRedisLogValues = new EbRedisLogValues(); 61 | List parameters = new List(); 62 | string query = @"SELECT prev_value, new_value FROM eb_redis_logs WHERE id = :logid"; 63 | parameters.Add(InfraConnectionFactory.ObjectsDB.GetNewParameter("logid", EbDbTypes.Int32, request.LogId)); 64 | EbDataTable dt = InfraConnectionFactory.ObjectsDB.DoQuery(query, parameters.ToArray()); 65 | EbRedisLogValues logValues = new EbRedisLogValues 66 | { 67 | Prev_val = dt.Rows[0][0].ToString(), 68 | New_val = dt.Rows[0][1].ToString() 69 | 70 | }; 71 | return new LogRedisViewChangesResponse { RedisLogValues = logValues }; 72 | } 73 | 74 | public RedisGroupDetailsResponse Get(RedisGetGroupDetails request) 75 | { 76 | Dictionary> grpdict = new Dictionary>(); 77 | string qry = @"select EO.obj_type, EO.display_name, EV.refid, EV.version_num FROM eb_objects EO , eb_objects_ver EV WHERE EO.id = EV.eb_objects_id AND (COALESCE(EO.eb_del, 'F')= 'F') order by EO.display_name"; 78 | EbDataTable dt = InfraConnectionFactory.ObjectsDB.DoQuery(qry); 79 | List l0 = new List(); 80 | List l1 = new List(); 81 | List l2 = new List(); 82 | List l3 = new List(); 83 | List l4 = new List(); 84 | List l5 = new List(); 85 | List L12 = new List(); 86 | List L14 = new List(); 87 | List L15 = new List(); 88 | List L16 = new List(); 89 | List L17 = new List(); 90 | List L18 = new List(); 91 | List L19 = new List(); 92 | List L20 = new List(); 93 | foreach (var item in dt.Rows) 94 | { 95 | EbRedisGroupDetails ob = new EbRedisGroupDetails 96 | { 97 | Obj_Type = Convert.ToInt32(item[0]), 98 | Disp_Name = Convert.ToString(item[1]), 99 | Refid = Convert.ToString(item[2]), 100 | Version = Convert.ToString(item[3]) 101 | 102 | }; 103 | 104 | if (ob.Obj_Type == 0) l0.Add(ob); 105 | else if (ob.Obj_Type == 1) l1.Add(ob); 106 | else if (ob.Obj_Type == 2) l2.Add(ob); 107 | else if (ob.Obj_Type == 3) l3.Add(ob); 108 | else if (ob.Obj_Type == 4) l4.Add(ob); 109 | else if (ob.Obj_Type == 5) l5.Add(ob); 110 | else if (ob.Obj_Type == 12) L12.Add(ob); 111 | else if (ob.Obj_Type == 14) L14.Add(ob); 112 | else if (ob.Obj_Type == 15) L15.Add(ob); 113 | else if (ob.Obj_Type == 16) L16.Add(ob); 114 | else if (ob.Obj_Type == 17) L17.Add(ob); 115 | else if (ob.Obj_Type == 18) L18.Add(ob); 116 | else if (ob.Obj_Type == 19) L19.Add(ob); 117 | else if (ob.Obj_Type == 20) L20.Add(ob); 118 | } 119 | grpdict.Add("Web Forms", l0); 120 | grpdict.Add("Display Block", l1); 121 | grpdict.Add("Data Readers", l2); 122 | grpdict.Add("Reports", l3); 123 | grpdict.Add("Data Writers", l4); 124 | grpdict.Add("Sql Functions", l5); 125 | grpdict.Add("Filter Dialogs", L12); 126 | grpdict.Add("User Controls", L14); 127 | grpdict.Add("Email Builders", L15); 128 | grpdict.Add("Table Visualizations", L16); 129 | grpdict.Add("Chart Visualizations", L17); 130 | grpdict.Add("Bot Forms", L18); 131 | grpdict.Add("Sms Builders", L19); 132 | grpdict.Add("Api Builders", L20); 133 | return new RedisGroupDetailsResponse { GroupsDict = grpdict }; 134 | } 135 | } 136 | } 137 | 138 | -------------------------------------------------------------------------------- /Services/ResetPasswordService.cs: -------------------------------------------------------------------------------- 1 | using ExpressBase.Objects.ServiceStack_Artifacts; 2 | using System; 3 | using ExpressBase.Security; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | using ExpressBase.Common.Data; 8 | using ServiceStack.Auth; 9 | using System.Data.Common; 10 | using ExpressBase.Common.Structures; 11 | using ExpressBase.Common.Extensions; 12 | using ExpressBase.Common.Security; 13 | 14 | namespace ExpressBase.ServiceStack.Services 15 | { 16 | public class ResetPasswordService : EbBaseService 17 | { 18 | // public MyAuthenticateResponse MyAuthenticateResponse { get; set; } 19 | 20 | public TwoFactorAuthServices TwoFAService { get; set; } 21 | 22 | public ResetPasswordService(IEbConnectionFactory _dbf) : base(_dbf) 23 | { 24 | this.TwoFAService = base.ResolveService(); 25 | } 26 | 27 | //public GetResetPwPageResponse Get(GetResetPwPageRequest request) 28 | //{ 29 | // GetResetPwPageResponse resp = new GetResetPwPageResponse(); 30 | // try 31 | // { 32 | // resp.RPWToken = EbTokenGenerator.GenerateToken(request.UserAuthId); 33 | // User u = GetUserObject(request.UserAuthId); 34 | // u.BearerToken = request.BearerToken; 35 | // u.RefreshToken = request.RefreshToken; 36 | // this.Redis.Set(request.UserAuthId, u); 37 | // } 38 | // catch (Exception e) 39 | // { 40 | // resp.ErrorMessage = e.Message; 41 | // Console.WriteLine(e.Message + e.StackTrace); 42 | // } 43 | // return resp; 44 | //} 45 | 46 | public ResetPwResponse Post(ResetPwRequest request) 47 | { 48 | ResetPwResponse resp = new ResetPwResponse(); 49 | try 50 | { 51 | this.EbConnectionFactory = new EbConnectionFactory(request.SolnId, this.Redis); 52 | string checkQ = string.Format("SELECT pwd FROM eb_users WHERE id = {0}", request.UserId); 53 | string currentPwd_db = this.EbConnectionFactory.DataDB.ExecuteScalar(checkQ); 54 | string currentPwdOldFormat = (request.PwDetails.CurrentPassword + request.Email).ToMD5Hash(); 55 | string NewPwdoldformat = (request.PwDetails.NewPassword + request.Email).ToMD5Hash(); 56 | if (currentPwd_db == currentPwdOldFormat || request.PwDetails.IsForgotPw) 57 | { 58 | if (currentPwd_db != NewPwdoldformat || request.PwDetails.IsForgotPw) 59 | { 60 | string NewPwdnewformat = (request.PwDetails.NewPassword.ToMD5Hash() + request.UserId.ToString() + request.SolnId).ToMD5Hash(); 61 | string updateQ = "UPDATE eb_users SET pwd = @oldformat , pw = @newformat , forcepwreset = 'F' WHERE id = @userid;"; 62 | DbParameter[] parameters = new DbParameter[] { 63 | this.EbConnectionFactory.DataDB.GetNewParameter("userid", EbDbTypes.Int32, request.UserId), 64 | this.EbConnectionFactory.DataDB.GetNewParameter("oldformat", EbDbTypes.String,NewPwdoldformat), 65 | this.EbConnectionFactory.DataDB.GetNewParameter("newformat", EbDbTypes.String, NewPwdnewformat)}; 66 | resp.Status = (this.EbConnectionFactory.DataDB.DoNonQuery(updateQ, parameters) == 1) ? true : false; 67 | } 68 | else 69 | { 70 | resp.ErrorMessage = "You cannot reset to a previous password. Make sure you entered a new password."; 71 | } 72 | } 73 | else 74 | { 75 | resp.ErrorMessage = "Current password is incorrect"; 76 | } 77 | } 78 | catch (Exception e) 79 | { 80 | resp.ErrorMessage = "Something went wrong"; 81 | Console.WriteLine(e.Message + e.StackTrace); 82 | } 83 | return resp; 84 | } 85 | 86 | 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /Services/SchedulerServices.cs: -------------------------------------------------------------------------------- 1 | using ExpressBase.Common; 2 | using ExpressBase.Common.Data; 3 | using ExpressBase.Common.Structures; 4 | using ExpressBase.Common.Connections; 5 | using ExpressBase.Objects.Services; 6 | using ExpressBase.Objects.ServiceStack_Artifacts; 7 | using ExpressBase.Scheduler.Jobs; 8 | using ServiceStack; 9 | using ServiceStack.Messaging; 10 | using System; 11 | using System.Collections.Generic; 12 | using System.Data.Common; 13 | using System.Linq; 14 | using System.Threading.Tasks; 15 | 16 | namespace ExpressBase.ServiceStack.Services 17 | { 18 | [Authenticate] 19 | public class SchedulerServices : EbBaseService 20 | { 21 | public SchedulerServices(IEbConnectionFactory _dbf, IMessageProducer _mqp, IMessageQueueClient _mqc) : base(_dbf, _mqp, _mqc) { } 22 | 23 | public ScheduleMQResponse Post(ScheduleMQRequest request) 24 | { 25 | MessageProducer3.Publish(new ScheduleRequest { Task = request.Task }); 26 | return null; 27 | } 28 | 29 | public UnscheduleMQResponse Post(UnscheduleMQRequest request) 30 | { 31 | UnscheduleMQResponse res = new UnscheduleMQResponse(); 32 | MessageProducer3.Publish(new UnscheduleRequest { TriggerKey = request.TriggerKey }); 33 | return res; 34 | 35 | } 36 | public RescheduleMQResponse Post(RescheduleMQRequest request) 37 | { 38 | RescheduleMQResponse res = new RescheduleMQResponse(); 39 | 40 | MessageProducer3.Publish(new RescheduleRequest { Task = request.Task, JobKey = request.JobKey, TriggerKey = request.TriggerKey }); 41 | 42 | EbConnectionFactory _ebConnectionFactory = new EbConnectionFactory(request.SolnId, this.Redis); 43 | string sql = "UPDATE eb_schedules SET task = @task, name=@name WHERE id = @id"; 44 | DbParameter[] parameters = { 45 | _ebConnectionFactory.DataDB.GetNewParameter("task", EbDbTypes.Json,EbSerializers.Json_Serialize(request.Task)), 46 | _ebConnectionFactory.DataDB.GetNewParameter("id", EbDbTypes.Int32,request.Id), 47 | _ebConnectionFactory.DataDB.GetNewParameter("name", EbDbTypes.String, request.Task.Name)}; 48 | var r = _ebConnectionFactory.DataDB.DoNonQuery(sql, parameters); 49 | return res; 50 | } 51 | 52 | public DeleteJobMQResponse Post(DeleteJobMQRequest request) 53 | { 54 | DeleteJobMQResponse res = new DeleteJobMQResponse(); 55 | MessageProducer3.Publish(new DeleteJobRequest { JobKey = request.JobKey }); 56 | 57 | EbConnectionFactory _ebConnectionFactory = new EbConnectionFactory(request.SolnId, this.Redis); 58 | 59 | string sql = "UPDATE eb_schedules SET status = @stat WHERE id = @id"; 60 | DbParameter[] parameters = { 61 | _ebConnectionFactory.DataDB.GetNewParameter("stat", EbDbTypes.Int32,(int)ScheduleStatuses.Deleted), 62 | _ebConnectionFactory.DataDB.GetNewParameter("id", EbDbTypes.Int32,request.Id) }; 63 | var r = _ebConnectionFactory.DataDB.DoNonQuery(sql, parameters); 64 | return res; 65 | } 66 | public GetAllUsersResponse Get(GetAllUsersRequest request) 67 | { 68 | GetAllUsersResponse res = new GetAllUsersResponse(); 69 | 70 | string sql = @"SELECT id, fullname FROM eb_users WHERE statusid = 0 AND eb_del ='F'; 71 | SELECT id, name FROM eb_usergroup WHERE eb_del ='F'"; 72 | var dt = this.EbConnectionFactory.DataDB.DoQueries(sql); 73 | 74 | Dictionary Users = new Dictionary(); 75 | Dictionary UserGroups = new Dictionary(); 76 | foreach (EbDataRow dr in dt.Tables[0].Rows) 77 | { 78 | Users[Convert.ToInt32(dr[0])] = dr[1].ToString(); 79 | } 80 | foreach (EbDataRow dr in dt.Tables[1].Rows) 81 | { 82 | UserGroups[Convert.ToInt32(dr[0])] = dr[1].ToString(); 83 | } 84 | res.Users = Users; 85 | res.UserGroups = UserGroups; 86 | 87 | //Slack user and group call 88 | 89 | res.SlackUsers = this.EbConnectionFactory.ChatConnection.GetAllUsers(); 90 | res.SlackChannels = this.EbConnectionFactory.ChatConnection.GetAllGroup(); 91 | 92 | return res; 93 | } 94 | 95 | public GetAllUsersResponse Get(GetAllSlackRequest request) 96 | { 97 | GetAllUsersResponse res = new GetAllUsersResponse(); 98 | 99 | return res; 100 | } 101 | 102 | public GetUserEmailsResponse Get(GetUserEmailsRequest request) 103 | { 104 | GetUserEmailsResponse res = new GetUserEmailsResponse(); 105 | 106 | string sql = EbConnectionFactory.DataDB.EB_GETUSEREMAILS; 107 | DbParameter[] parameters = { EbConnectionFactory.DataDB.GetNewParameter("userids", EbDbTypes.String, (request.UserIds==null)?string.Empty:request.UserIds), 108 | EbConnectionFactory.DataDB.GetNewParameter("groupids", EbDbTypes.String, ( request.UserGroupIds == null)?string.Empty:request.UserGroupIds) }; 109 | 110 | var dt = this.EbConnectionFactory.DataDB.DoQueries(sql, parameters); 111 | Dictionary Users = new Dictionary(); 112 | Dictionary UserGroups = new Dictionary(); 113 | foreach (EbDataRow dr in dt.Tables[0].Rows) 114 | { 115 | Users[Convert.ToInt32(dr[0])] = dr[1].ToString(); 116 | } 117 | foreach (EbDataRow dr in dt.Tables[1].Rows) 118 | { 119 | UserGroups[Convert.ToInt32(dr[0])] = dr[1].ToString(); 120 | } 121 | res.UserEmails = Users; 122 | res.UserGroupEmails = UserGroups; 123 | 124 | return res; 125 | } 126 | 127 | public GetSchedulesOfSolutionResponse Get(GetSchedulesOfSolutionRequest request) 128 | { 129 | GetSchedulesOfSolutionResponse resp = new GetSchedulesOfSolutionResponse(); 130 | List scheduleList = new List(); 131 | string sql = ""; 132 | 133 | if (request.ObjectId > 0) 134 | { 135 | sql = @"SELECT * FROM eb_schedules ES ,eb_users EU 136 | WHERE EU.id = ES.created_by 137 | AND obj_id = @obj_id AND status != 3 138 | ORDER BY ES.id;"; 139 | } 140 | else if (request.ObjectId == -1) 141 | { 142 | sql = @"SELECT * FROM eb_schedules ES ,eb_users EU 143 | WHERE EU.id = ES.created_by AND status != 3 144 | ORDER BY ES.id;"; 145 | } 146 | 147 | DbParameter[] parameters = { 148 | EbConnectionFactory.DataDB.GetNewParameter("obj_id", EbDbTypes.Int32,request.ObjectId) 149 | }; 150 | EbDataSet dt = this.EbConnectionFactory.DataDB.DoQueries(sql, parameters); 151 | foreach (EbDataRow dr in dt.Tables[0].Rows) 152 | { 153 | EbSchedule sch = new EbSchedule 154 | { 155 | Id = Convert.ToInt32(dr[0]), 156 | Task = EbSerializers.Json_Deserialize(dr[1].ToString()), 157 | CreatedBy = dr[34].ToString(), 158 | CreatedAt = Convert.ToDateTime(dr[3]), 159 | JobKey = dr[5].ToString(), 160 | TriggerKey = dr[6].ToString(), 161 | Status = (ScheduleStatuses)Convert.ToInt32(dr[7]), 162 | Name = dr[9].ToString() 163 | }; 164 | scheduleList.Add(sch); 165 | } 166 | resp.Schedules = scheduleList; 167 | 168 | return resp; 169 | } 170 | } 171 | 172 | [Restrict(InternalOnly = true)] 173 | class SchedulesAndSolutionServices : EbMqBaseService 174 | { 175 | public SchedulesAndSolutionServices(IMessageProducer _mqp, IMessageQueueClient _mqc) : base(_mqp, _mqc) { } 176 | 177 | public ScheduleMQResponse Post(AddSchedulesToSolutionRequest request) 178 | { 179 | EbConnectionFactory _ebConnectionFactory = new EbConnectionFactory(request.SolnId, this.Redis); 180 | 181 | string sql = @"INSERT INTO eb_schedules(task, created_by, created_at, eb_del, jobkey, triggerkey, status, obj_id, name) 182 | VALUES(@task, @created_by, NOW(), 'F', @jobkey, @triggerkey, @status, @obj_id, @name)"; 183 | DbParameter[] parameters = { _ebConnectionFactory.DataDB.GetNewParameter("task", EbDbTypes.Json,EbSerializers.Json_Serialize(request.Task)), 184 | _ebConnectionFactory.DataDB.GetNewParameter("created_by", EbDbTypes.Int32, request.Task.JobArgs.UserId), 185 | _ebConnectionFactory.DataDB.GetNewParameter("jobkey", EbDbTypes.String, request.JobKey), 186 | _ebConnectionFactory.DataDB.GetNewParameter("triggerkey", EbDbTypes.String, request.TriggerKey), 187 | _ebConnectionFactory.DataDB.GetNewParameter("status", EbDbTypes.Int32, (int)request.Status) , 188 | _ebConnectionFactory.DataDB.GetNewParameter("obj_id", EbDbTypes.Int32, (int)request.ObjId), 189 | _ebConnectionFactory.DataDB.GetNewParameter("name", EbDbTypes.String, request.Name)}; 190 | var dt = _ebConnectionFactory.DataDB.DoNonQuery(sql, parameters); 191 | 192 | return null; 193 | } 194 | } 195 | } 196 | -------------------------------------------------------------------------------- /Services/Test.cs: -------------------------------------------------------------------------------- 1 | using ExpressBase.Common; 2 | using ExpressBase.Common.Data; 3 | using ExpressBase.Objects.ServiceStack_Artifacts; 4 | using ServiceStack; 5 | using ServiceStack.Auth; 6 | using ServiceStack.Logging; 7 | using ServiceStack.Messaging; 8 | using System; 9 | using System.Collections.Generic; 10 | using System.Data.Common; 11 | using System.Linq; 12 | using System.Threading.Tasks; 13 | 14 | namespace ExpressBase.ServiceStack.Services 15 | { 16 | [Authenticate] 17 | public class Test : EbBaseService 18 | { 19 | public Test(IEbConnectionFactory _dbf, IMessageProducer _mqp, IMessageQueueClient _mqc) : base(_dbf, _mqp, _mqc) { } 20 | 21 | public TestResponse Any(TestRequest request) 22 | { 23 | ILog log = LogManager.GetLogger(GetType()); 24 | using (var con = EbConnectionFactory.DataDB.GetNewConnection()) 25 | { 26 | log.Info("Connection"); 27 | con.Open(); 28 | log.Info(".............." + con + "Connection Opened"); 29 | // string sql = "INSERT INTO testtb (name) VALUES ('BINI')"; 30 | 31 | try 32 | { 33 | string sql1 = "INSERT INTO test_tbl(Name,number) VALUES ('ref',eb_currval(test_tbl_id_seq));"; 34 | //string sql2 = "INSERT INTO test_tbl(name,number) VALUES ('ref',123);INSERT INTO test_tbl(name,number) VALUES ('ref',eb_currval(test_tbl_id_seq));"; 35 | var cmd = con.CreateCommand(); 36 | cmd.CommandText = sql1; 37 | cmd.ExecuteNonQuery(); 38 | } 39 | catch 40 | { 41 | } 42 | } 43 | return null; 44 | } 45 | } 46 | 47 | //[Authenticate] 48 | //public class ReqstarsService : Service 49 | //{ 50 | // public object Get(ApiTestReq request) 51 | // { 52 | // var authProvider = (ApiKeyAuthProvider)AuthenticateService.GetAuthProvider(ApiKeyAuthProvider.Name); 53 | 54 | // var auth_api = (ApiKeyAuthProvider)AuthenticateService.GetAuthProvider(ApiKeyAuthProvider.Name); 55 | 56 | // var authRepo = TryResolve(); 57 | 58 | // List apiKeys = auth_api.GenerateNewApiKeys("hairocraft_stagging:hairocraft123@gmail.com:uc"); 59 | 60 | // authRepo.StoreAll(apiKeys); 61 | 62 | // return new UnniTest(); 63 | // } 64 | //} 65 | } 66 | -------------------------------------------------------------------------------- /Services/VrgsTestService.cs: -------------------------------------------------------------------------------- 1 | //using ExpressBase.Common; 2 | //using ExpressBase.Common.Data; 3 | //using ExpressBase.Common.Extensions; 4 | //using ExpressBase.Common.Structures; 5 | //using ExpressBase.Objects.ServiceStack_Artifacts; 6 | //using System; 7 | //using System.Collections.Generic; 8 | //using System.Data.Common; 9 | //using System.IO; 10 | //using System.Linq; 11 | //using System.Threading.Tasks; 12 | 13 | //namespace ExpressBase.ServiceStack.Services 14 | //{ 15 | // public class VrgsTestService : EbBaseService 16 | // { 17 | // public VrgsTestService(IEbConnectionFactory _dbf) : base(_dbf) { } 18 | 19 | // public SaveSvgResponse Post(SaveSvgRequest svgreq) 20 | // { 21 | // SaveSvgResponse svgres = new SaveSvgResponse(); 22 | // try 23 | // { 24 | // List Paramtr = new List(); 25 | // string[] ColArray = new string[] { "svgstring", "bgimg_bytea" }; 26 | 27 | // string sql = @"INSERT INTO vrgs_floorplan(svgstring,bgimg_bytea) 28 | // VALUES( 29 | // :svgst, 30 | // :imgbytea 31 | // )RETURNING id;"; 32 | // //string sql = @"INSERT INTO vrgs_floorplan({0}) 33 | // // VALUES( 34 | // // :svgst, 35 | // // :imgbytea 36 | // // )RETURNING id;"; 37 | // DbParameter[] parameters = { 38 | // this.InfraConnectionFactory.DataDB.GetNewParameter("svgst", EbDbTypes.String, svgreq.Txtsvg), 39 | // this.InfraConnectionFactory.DataDB.GetNewParameter("imgbytea", EbDbTypes.Bytea, svgreq.BgFile) 40 | // }; 41 | // //Paramtr.Add(this.InfraConnectionFactory.DataDB.GetNewParameter("svgst", EbDbTypes.String, svgreq.Txtsvg)); 42 | // //Paramtr.Add(this.InfraConnectionFactory.DataDB.GetNewParameter("imgbytea", EbDbTypes.Bytea, svgreq.BgFile)); 43 | // //DbParameter[] parameters = Paramtr.ToArray(); 44 | // EbDataTable dt = this.InfraConnectionFactory.DataDB.DoQuery(sql, parameters); 45 | // var rslt = Convert.ToInt32(dt.Rows[0][0]); 46 | // } 47 | // catch (Exception e) 48 | // { 49 | // Console.WriteLine("Exception: " + e.Message + e.StackTrace); 50 | // } 51 | // return svgres; 52 | // } 53 | 54 | // public RetriveSVGResponse post(RetriveSVGRequest rtsvg) 55 | // { 56 | // RetriveSVGResponse rsv = new RetriveSVGResponse(); 57 | // try 58 | // { 59 | 60 | // string sql1 = @"SELECT 61 | // svgstring, 62 | // bgimg_bytea 63 | // FROM 64 | // vrgs_floorplan 65 | // WHERE 66 | // id=:svgid"; 67 | // DbParameter[] param = 68 | // { 69 | // this.InfraConnectionFactory.DataDB.GetNewParameter("svgid", EbDbTypes.Int32, rtsvg.Idno) 70 | // }; 71 | // EbDataTable dt = this.InfraConnectionFactory.DataDB.DoQuery(sql1, param); 72 | // if (dt.Rows.Count > 0) 73 | // { 74 | // rsv.SvgPolyData = dt.Rows[0][0].ToString(); 75 | // var fileBase64Data = Convert.ToBase64String((byte[])(dt.Rows[0][1])); 76 | // //rsv.FileDataURL = fileBase64Data; 77 | // rsv.FileDataURL = string.Format("data:image/png;base64,{0}", fileBase64Data); 78 | 79 | // } 80 | // } 81 | // catch (Exception e) 82 | // { 83 | // Console.WriteLine("Exception: " + e.Message + e.StackTrace); 84 | // } 85 | 86 | // return rsv; 87 | // } 88 | 89 | 90 | 91 | 92 | // } 93 | //} 94 | -------------------------------------------------------------------------------- /robots.txt: -------------------------------------------------------------------------------- 1 | User-agent: * 2 | Disallow: / --------------------------------------------------------------------------------