/// <summary>
        /// Read the record from server stream
        /// </summary>
        /// <param name="clientSocket">Connected Socket</param>
        /// <param name="_msgCallBack">Callback function on new message</param>
        public void readStream(object clientSocket, Action <string, string> _msgCallBack, [Optional] CancellationToken _cancelToken)
        {
            _msgCallBack("<LOG>Fetching Records...", recordType);
            try
            {
                while (true)
                {
                    if (_cancelToken != null && _cancelToken.IsCancellationRequested)
                    {
                        connectDone.Set();
                        ((TcpClient)clientSocket).Close();
                        return;
                    }

                    var msg = ConnectionUtility.ReadClientStream((TcpClient)clientSocket);
                    if (!string.IsNullOrEmpty(msg))
                    {
                        _msgCallBack(msg, recordType);
                        ConnectionUtility.WriteClientStream((TcpClient)clientSocket, "<ACK>");
                    }
                    else
                    {
                        break;
                    }
                }
                _msgCallBack(((TcpClient)clientSocket).Connected ? "<LOG>Finished Processing records." : "<LOG>Connection Terminated.", recordType);
            }
            catch (Exception ex)
            {
            }
            finally{
                connectDone.Set();
                connectDone.Reset();
            }
        }
        /// <summary>
        /// Establish a connection with the server
        /// </summary>
        /// <param name="_ipAddress"></param>
        /// <param name="port"></param>
        /// <param name="_msgCallBack"></param>
        public void ConnectServer(IPAddress _ipAddress, int port, Action <string, string> _msgCallBack, [Optional] CancellationToken _cancelToken)
        {
            _msgCallBack(string.Format("<LOG>Attempting to connect {0}:{1}...", _ipAddress.ToString(), port.ToString()), "Green");

            int _retryCount = 0;

            while (true)
            {
                try
                {
                    if (_cancelToken != null && _cancelToken.IsCancellationRequested)
                    {
                        break;
                    }
                    clientSocket.Connect(_ipAddress, port);
                    ConnectionUtility.WriteClientStream(clientSocket, recordType);
                    _msgCallBack("<LOG>Connection established with server", "Green");
                    ThreadPool.QueueUserWorkItem(o => readStream(clientSocket, _msgCallBack, _cancelToken));
                    connectDone.WaitOne();
                    break;
                }
                catch (Exception ex)
                {
                    _retryCount++;
                    if (_retryCount > 10)
                    {
                        _msgCallBack("<LOG>Failed to connect the server specified, Retrying...", "Red");
                        _retryCount = 0;
                    }
                }
            }
        }
 public IActionResult GetMessageData()
 {
     try
     {
         var email = User.Claims.First(x => x.Type == "Email");
         return(Ok($"{ConnectionUtility.GetEmailPassword()} {ConnectionUtility.GetFromEmail()} {email}"));
     }
     catch (Exception ex)
     {
         return(Problem("Something is broke, yo"));
     }
 }
Example #4
0
        public void Awake()
        {
            // Taken from DefaultWorldInitalization.cs
            SetupInjectionHooks();                                               // Register hybrid injection hooks
            PlayerLoopManager.RegisterDomainUnload(DomainUnloadShutdown, 10000); // Clean up worlds and player loop

            Application.targetFrameRate = targetFrameRate;
            Worker.OnConnect           += w => Debug.Log($"{w.WorkerId} is connecting");
            Worker.OnDisconnect        += w => Debug.Log($"{w.WorkerId} is disconnecting");

            // Setup template to use for player on connecting client
            PlayerLifecycleConfig.CreatePlayerEntityTemplate = PlayerTemplate.CreatePlayerEntityTemplate;

            if (Application.isEditor)
            {
                var config = new ReceptionistConfig
                {
                    WorkerType = SystemConfig.UnityGameLogic,
                };
                CreateWorker(config, new Vector3(500, 0, 0));
                config = new ReceptionistConfig
                {
                    WorkerType = SystemConfig.UnityClient,
                };
                CreateWorker(config, Vector3.zero);
            }
            else
            {
                var commandLineArguments = Environment.GetCommandLineArgs();
                Debug.LogFormat("Command line {0}", string.Join(" ", commandLineArguments.ToArray()));
                var commandLineArgs = CommandLineUtility.ParseCommandLineArgs(commandLineArguments);
                var config          = ConnectionUtility.CreateConnectionConfigFromCommandLine(commandLineArgs);
                CreateWorker(config, Vector3.zero);
            }

            if (World.AllWorlds.Count <= 0)
            {
                throw new InvalidConfigurationException(
                          "No worlds have been created, due to invalid worker types being specified. Check the config in" +
                          "Improbable -> Configure editor workers.");
            }

            var worlds = World.AllWorlds.ToArray();

            ScriptBehaviourUpdateOrder.UpdatePlayerLoop(worlds);
            // Systems don't tick if World.Active isn't set
            World.Active = worlds[0];
        }
Example #5
0
        public void Send(string subject, string body, string emailTo)
        {
            try
            {
                var client = new SmtpClient("smtp.gmail.com", 587)
                {
                    UseDefaultCredentials = false,
                    Credentials           = new NetworkCredential(ConnectionUtility.GetFromEmail(), ConnectionUtility.GetEmailPassword()),
                    EnableSsl             = true
                };

                client.Send(ConnectionUtility.GetFromEmail(), emailTo, subject, body);
            }
            catch (Exception ex)
            {
                //TODO: Logging
            }
        }
Example #6
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  builder => builder.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials());
            });

            services.AddOptions();

            // Add framework services.
            services.AddMvc(
                config =>
            {
                config.Filters.Add(typeof(GlobalExceptionHandler));
            }
                );
            services.AddMvc();

            services.AddSingleton <IConfiguration>(Configuration);

            //To get Direct Mail Connection String
            ConnectionUtility dmConnectionUtility        = new ConnectionUtility(Configuration, true);
            string            directMailConnectionString = dmConnectionUtility.DBSQLConnectionString;

            //To get Insert Card Connection String
            ConnectionUtility icConnectionUtility        = new ConnectionUtility(Configuration, false);
            string            insertCardConnectionString = icConnectionUtility.DBSQLConnectionString;

            services.AddDbContext <DMContext>(options => options.UseSqlServer(directMailConnectionString));

            //services.AddScoped<IDMFlashBudgetRepository, DMFlashBudgetRepository>();

            // swagger support
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Campaign Budget Tool API", Version = "v1"
                });
                c.IncludeXmlComments(GetXmlCommentsPath());
            });

            var key        = Encoding.ASCII.GetBytes(Configuration.GetSection("Jwt").GetSection("Key").Value);
            var signingKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(key);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = signingKey,
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    RequireExpirationTime    = false,
                    ValidateLifetime         = false
                };
            });
        }
Example #7
0
        public void Awake()
        {
            InitializeWorkerTypes();
            // Taken from DefaultWorldInitalization.cs
            SetupInjectionHooks();                                               // Register hybrid injection hooks
            PlayerLoopManager.RegisterDomainUnload(DomainUnloadShutdown, 10000); // Clean up worlds and player loop

            Application.targetFrameRate = TargetFrameRate;
            if (Application.isEditor)
            {
#if UNITY_EDITOR
                var workerConfigurations =
                    AssetDatabase.LoadAssetAtPath <ScriptableWorkerConfiguration>(ScriptableWorkerConfiguration
                                                                                  .AssetPath);
                foreach (var workerConfig in workerConfigurations.WorkerConfigurations)
                {
                    if (!workerConfig.IsEnabled)
                    {
                        continue;
                    }

                    var worker = WorkerRegistry.CreateWorker(workerConfig.Type, $"{workerConfig.Type}-{Guid.NewGuid()}",
                                                             workerConfig.Origin);
                    Workers.Add(worker);
                }

                connectionConfig = new ReceptionistConfig();
                connectionConfig.UseExternalIp = workerConfigurations.UseExternalIp;
#endif
            }
            else
            {
                var commandLineArguments = System.Environment.GetCommandLineArgs();
                Debug.LogFormat("Command line {0}", string.Join(" ", commandLineArguments.ToArray()));
                var commandLineArgs = CommandLineUtility.ParseCommandLineArgs(commandLineArguments);
                var workerType      =
                    CommandLineUtility.GetCommandLineValue(commandLineArgs, RuntimeConfigNames.WorkerType,
                                                           string.Empty);
                var workerId =
                    CommandLineUtility.GetCommandLineValue(commandLineArgs, RuntimeConfigNames.WorkerId,
                                                           string.Empty);

                // because the launcher does not pass in the worker type as an argument
                var worker = workerType.Equals(string.Empty)
                    ? WorkerRegistry.CreateWorker <UnityClient>(
                    workerId: null,     // The worker id for the UnityClient will be auto-generated.
                    origin: new Vector3(0, 0, 0))
                    : WorkerRegistry.CreateWorker(workerType, workerId, new Vector3(0, 0, 0));

                Workers.Add(worker);

                connectionConfig = ConnectionUtility.CreateConnectionConfigFromCommandLine(commandLineArgs);
            }

            if (World.AllWorlds.Count <= 0)
            {
                throw new InvalidConfigurationException(
                          "No worlds have been created, due to invalid worker types being specified. Check the config in" +
                          "Improbable -> Configure editor workers.");
            }

            var worlds = World.AllWorlds.ToArray();
            ScriptBehaviourUpdateOrder.UpdatePlayerLoop(worlds);
            // Systems don't tick if World.Active isn't set
            World.Active = worlds[0];
        }
Example #8
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped <IAuthProvider, AuthProvider>();
            services.AddScoped <ITransactionProvider, TransactionProvider>();
            services.AddScoped <IPlayerProvider, PlayerProvider>();
            services.AddScoped <ISessionProvider, SessionProvider>();
            services.AddScoped <IMessageProvider, MessageProvider>();

            services.AddCors();
            services.AddMvc(option => option.EnableEndpointRouting = false);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(ConnectionUtility.GetSharedSecret())),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });
        }
        public TransactionRepo()
        {
            var connString = ConnectionUtility.GetPostGresConnString();

            DbProvider = new PostgresProvider(connString);
        }
Example #10
0
        public AuthResponse Authenticate(string user, string password)
        {
            var userData = new UsersRepo().GetUser(user.Trim());

            var goodPassword = PasswordUtility.VerfiyHash(userData.PasswordHash, password.Trim());

            if (goodPassword)
            {
                var tokenHandler    = new JwtSecurityTokenHandler();
                var tokenIssueDate  = DateTime.Now;
                var tokenExpiration = DateTime.Now.AddHours(12);

                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new List <Claim> {
                        new Claim("User", user.Trim().ToLower()), new Claim("UserId", userData.UserId), new Claim("Email", userData.Email)
                    }),
                    Expires = tokenExpiration,
                    //TODO: Get this out of a config or DB
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(ConnectionUtility.GetSharedSecret())), SecurityAlgorithms.HmacSha256Signature)
                };

                var token = tokenHandler.CreateToken(tokenDescriptor);

                return(new AuthResponse
                {
                    Authenticated = true,
                    Username = user,
                    AccessToken = tokenHandler.WriteToken(token),
                    TokenIssueDate = tokenIssueDate,
                    TokenExpirationDate = tokenExpiration
                });
            }
            else
            {
                return(new AuthResponse {
                    Authenticated = false, Username = user
                });
            }
        }
Example #11
0
 public ClientSender(IScsClient client, RequestReplyMessenger <IScsClient> clientRequestReply)
 {
     _clientUtility = new ConnectionUtility(client, clientRequestReply);
 }