Exemplo n.º 1
0
        public ClientForm()
        {
            InitializeComponent();

            name = new Random().Next(1000, 10000).ToString();

            Text = "Client " + name;

            client = new SGClient();

            client.Tags["name"] = name;

            client.Connected += (s, e) =>
            {
                Invoke(new Action(() =>
                {
                    tbPort.ReadOnly    = true;
                    tbAddress.ReadOnly = true;
                    logPanel.Info("Connected");
                    tbConnect.Text = "Connected";
                }));
            };
            client.Disconnected += (s, e) =>
            {
                Invoke(new Action(() =>
                {
                    tbAddress.ReadOnly = false;
                    tbPort.ReadOnly    = false;
                    logPanel.Info("Disconnected");
                    tbConnect.Text = "Connect";
                }));

                connected = false;
            };
            client.AuthRespond += (s, e) =>
            {
                if (e.IsRejected)
                {
                    logPanel.Error("Auth Rejected");
                }
                else
                {
                    logPanel.Info("Auth Successful");
                }
            };
            client.DataReceived += (s, e) =>
            {
                logPanel.Message(e.Data.Head, e.Data.Body);
            };


            lblName.Text = name;

            tbMessage.AutoCompleteMode         = AutoCompleteMode.Append;
            tbMessage.AutoCompleteCustomSource = new AutoCompleteStringCollection();
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            var name = new Random().Next(1000, 10000).ToString();

            try
            {
                var client = new SGClient();

                client.AuthToken    = name;
                client.Tags["name"] = "client_" + name;

                Info($"Starting client {name}");

                client.AuthRespond += (s, e) =>
                {
                    if (e.IsRejected)
                    {
                        Info("Auth rejected");
                    }
                    else
                    {
                        Info("Auth successful");
                    }
                };

                client.Disconnected += (s, e) =>
                {
                    Info("Disconnected");
                    client.ReconnectAsync(int.MaxValue);
                };

                client.Connected += (s, e) => Info("Connected to server");


                var res = client.Connect(9999);

                client.DataReceived += (s, e) =>
                {
                    if (e.Data.Head != name)
                    {
                        Message(e.Data.Head, e.Data.Body);
                    }
                };

                if (client.IsConnected())
                {
                    while (true)
                    {
                        Console.Write(">");
                        var line = Console.ReadLine();

                        var response = client.Request(name, line);
                        if (response.IsOK)
                        {
                            Log("message was successfully sent");
                        }
                        else
                        {
                            Log("message send respond with an error");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Error(ex.Message, ex.StackTrace);
            }

            Console.WriteLine("finished");
            Console.ReadLine();
        }
Exemplo n.º 3
0
 public ClientConnectionEventArgs(SGClient client, string reason = null) : base(reason)
 {
     Client = client;
 }
 public SGDataController(SGClient factory, DataContext conte)
 {
     sgClient = factory;
     context  = conte;
 }
Exemplo n.º 5
0
        void Accept()
        {
            Task.Run((() =>
            {
                try
                {
                    while (socket.IsBound)
                    {
                        socket.Listen(1);
                        var sock = socket.Accept();

                        lock (this)
                        {
                            var client = new SGClient(sock);
                            client.AuthRequested += (s, e) =>
                            {
                                var args = new ClientAuthRequestedEventArgs(client, e.AuthToken, e.Response);
                                ClientAuthRequested?.Invoke(this, args);

                                e.Response = args.Response;
                                e.Reject = args.Reject || (args.Response != null && args.Response.IsError);
                                if (!e.Reject)
                                {
                                    client.Disconnected += (s1, e1) =>
                                    {
                                        lock (this)
                                        {
                                            clients.Remove(client);
                                        }

                                        ClientDisconnected?.Invoke(this, new ClientConnectionEventArgs(client, e1.Reason));
                                    };

                                    lock (this)
                                    {
                                        clients.Add(client);
                                    }

                                    ClientConnected?.Invoke(this, new ClientConnectionEventArgs(client));
                                }
                            };
                            client.Listen();
                            Task.Delay(AuthenticationTimeout).ContinueWith(t =>
                            {
                                if (!client.IsAuthorised)
                                {
                                    client.Close();
                                }
                            });
                        }
                    }
                }
                catch (Exception ex)
                {
                    _ = ex;
                    Stopped?.Invoke(this, EventArgs.Empty);
                }
                finally
                {
                    foreach (var client in Clients)
                    {
                        try
                        {
                            client.Close();
                        }
                        catch (Exception ex)
                        {
                            _ = ex;
                        }
                    }
                    clients.Clear();
                }
            }));
        }
 public ClientAuthRequestedEventArgs(SGClient client, string token, Response response)
 {
     Client   = client;
     Token    = token;
     Response = response;
 }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddDefaultPolicy(config =>
                {
                    config.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().WithExposedHeaders(Headers);
                });
            });

            services.AddAuthentication("Bearer").AddJwtBearer("Bearer", config =>
            {
                config.Authority            = Configuration["Services:Authority"];
                config.Audience             = "Appraisal";
                config.RequireHttpsMetadata = false;
            });
            services.AddHttpClient("EmployeeService", config =>
            {
                config.BaseAddress = new Uri(Configuration["Services:employee"]);
                config.DefaultRequestHeaders.Clear();
                config.DefaultRequestHeaders.Add("Accept", "application/json");
            }).AddTransientHttpErrorPolicy(p => p.WaitAndRetryAsync(5, _ => TimeSpan.FromMilliseconds(500)));

            services.AddHttpClient("discoveryEndpoint", config =>
            {
                config.BaseAddress = new Uri(Configuration["Services:Authority"]);
                config.DefaultRequestHeaders.Clear();
                config.DefaultRequestHeaders.Add("Accept", "application/json");
            });
            services.AddHttpClient("Auth", config =>
            {
                config.BaseAddress = new Uri(Configuration["Services:Auth"]);
                config.DefaultRequestHeaders.Clear();
                config.DefaultRequestHeaders.Add("Accept", "application/json");
            });

            //services.AddHttpContextAccessor();

            services.AddTransient <IDbContext, EdgeAppraisalContext>(ctx => EdgeAppraisalContext.Create(
                                                                         Configuration.GetSection("DefaultConnection:ConnectionString").Value,
                                                                         Configuration.GetSection("DefaultConnection:DataBaseName").Value));

            services.AddTransient <ISGClient, SGClient>(ctx => SGClient.Create(
                                                            Configuration.GetSection("SendGrid:SENDGRID_API_KEY").Value));

            services.AddTransient(typeof(EmailDispatcher));
            services.AddTransient <IEmailSender, EmailSender>();
            services.AddTransient <IKeyResultArea, KeyResultAreaService>();
            services.AddTransient <IAppraisalConfig, AppraisalConfigService>();
            services.AddTransient <IAppraisalResult, AppraisalResultService>();
            services.AddTransient <ITeamRepository, TeamService>();
            services.AddTransient <IAppraisalFinalResult, AppraisalFinalResultService>();
            services.AddTransient <ICoreValue, CoreValueService>();
            services.AddScoped <ITokenAccesor, TokenAccessorService>();
            services.AddTransient(typeof(AuthService));

            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

            services.Configure <MvcOptions>(config =>
            {
                var newtonsoftJsonOutputFormatter = config.OutputFormatters.OfType <NewtonsoftJsonOutputFormatter>()?.FirstOrDefault();
                if (newtonsoftJsonOutputFormatter != null)
                {
                    newtonsoftJsonOutputFormatter.SupportedMediaTypes.Add("application/vnd.marvin.hateoas+json");
                }
            });
            services.AddControllers(setupAction =>
            {
                setupAction.ReturnHttpNotAcceptable = true;
            })
            .AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver())
            .AddXmlDataContractSerializerFormatters();
        }
        public void ConfigureServices(IServiceCollection services)
        {
            var AuthConnectionString      = configuration.GetConnectionString("Auth");
            var Identity4ConnectionString = configuration.GetConnectionString("Identity4");

            services.AddCors(options =>
            {
                options.AddDefaultPolicy(cors =>
                                         cors.AllowAnyOrigin()
                                         .AllowAnyMethod()
                                         .AllowAnyHeader()
                                         );
            });

            services.AddDbContext <EdgeDbContext>(config => { config.UseSqlServer(AuthConnectionString, options => { options.EnableRetryOnFailure(); }); })
            .AddIdentity <ApplicationUser, ApplicationRole>(config =>
            {
                config.Password.RequiredLength         = 4;
                config.Password.RequireDigit           = false;
                config.Password.RequiredUniqueChars    = 0;
                config.Password.RequireNonAlphanumeric = false;
                config.Password.RequireUppercase       = false;
                config.Password.RequireLowercase       = false;
            })
            .AddEntityFrameworkStores <EdgeDbContext>()
            .AddDefaultTokenProviders();

            services.ConfigureApplicationCookie(config =>
            {
                config.LoginPath   = "/Auth/Authenticate";
                config.Cookie.Name = "IdentityServer.Cookie";
                config.LogoutPath  = "/Auth/signout";
            });
            var assembly = typeof(Startup).Assembly.GetName().Name;

            //var certificate = new X509Certificate2()


            services.AddIdentityServer()
            .AddCorsPolicyService <CorsPolicyImplementation>()
            .AddAspNetIdentity <ApplicationUser>()
            .AddConfigurationStore(options =>
            {
                options.ConfigureDbContext = b => b.UseSqlServer(Identity4ConnectionString,
                                                                 sql => sql.MigrationsAssembly(assembly));
            })
            .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = b => b.UseSqlServer(Identity4ConnectionString,
                                                                 sql => sql.MigrationsAssembly(assembly));
            })
            .AddDeveloperSigningCredential();
            //.AddSigningCredential()

            services.AddTransient <ISGClient, SGClient>(ctx => SGClient.Create(
                                                            configuration.GetSection("SendGrid:SENDGRID_API_KEY").Value));

            services.AddTransient(typeof(EmailDispatcher));
            services.AddTransient <IEmailSender, EmailService>();
            services.AddTransient <IAuthInterface, AuthServices>();
            services.AddTransient <IExternalServiceInterface, ExternalApprisalService>();

            services.AddControllersWithViews()
            .AddRazorRuntimeCompilation();
        }