Ejemplo n.º 1
0
        public DaemonService(
            ILogger <DaemonService> logger,
            Simulator simulator,
            Scheduler scheduler)
        {
            _logger = logger;


            if (!string.IsNullOrEmpty(Shared.Configuration["aws_access_key_id"]) &&
                !string.IsNullOrEmpty(Shared.Configuration["aws_secret_access_key"]))
            {
                var credentialFile = new NetSDKCredentialsFile();
                var option         = new CredentialProfileOptions
                {
                    AccessKey = Shared.Configuration["aws_access_key_id"],
                    SecretKey = Shared.Configuration["aws_secret_access_key"]
                };
                var profile = new CredentialProfile("default", option)
                {
                    Region = Amazon.RegionEndpoint.EUWest1
                };
                credentialFile.RegisterProfile(profile);
            }

            var serviceName = Shared.Configuration["ServiceName"];

            if ("simulator".Equals(serviceName, StringComparison.OrdinalIgnoreCase))
            {
                _task = simulator;
            }
            else
            {
                _task = scheduler;
            }
        }
        public async Task <IActionResult> ReplicationDetails(String tableName)
        {
            NetSDKCredentialsFile    credentialsFile = new NetSDKCredentialsFile();
            CredentialProfileOptions options         = new CredentialProfileOptions();

            options.AccessKey = HttpContext.Session.GetString("AccessKey");
            options.SecretKey = HttpContext.Session.GetString("SecretKey");
            credentialsFile.RegisterProfile(new CredentialProfile("default", options));

            DescribeTableStatisticsRequest request = new DescribeTableStatisticsRequest();

            request.ReplicationTaskArn = HttpContext.Session.GetString("ReplicationTaskArn");

            request.Filters.Add(new Filter {
                Name = "table-name", Values = { tableName }
            });

            var statistics = await DbMigrationService.DescribeTableStatisticsAsync(request);

            var item = statistics.TableStatistics.SingleOrDefault(t => t.TableName == tableName);

            if (item == null)
            {
                return(NotFound());
            }

            return(View(new DisplayTableStatistics(item, displayIcon(item.TableName), statusColor(item))));
        }
Ejemplo n.º 3
0
        public async Task <InvokeResult> InitAsync(DataStream stream)
        {
            _stream = stream;
            var options = new CredentialProfileOptions
            {
                AccessKey = stream.AwsAccessKey,
                SecretKey = stream.AwsSecretKey
            };

            var profile    = new Amazon.Runtime.CredentialManagement.CredentialProfile($"awsprofile_{stream.Id}", options);
            var netSDKFile = new NetSDKCredentialsFile();

            netSDKFile.RegisterProfile(profile);

            var creds = AWSCredentialsFactory.GetAWSCredentials(profile, netSDKFile);

            try
            {
                _s3Client = new AmazonS3Client(creds, AWSRegionMappings.MapRegion(stream.AwsRegion));
                await _s3Client.EnsureBucketExistsAsync(stream.S3BucketName);
            }
            catch (AmazonS3Exception amazonS3Exception)
            {
                _logger.AddException("AWSS3Connector_InitAsync", amazonS3Exception);
                return(InvokeResult.FromException("AWSS3Connector_InitAsync", amazonS3Exception));
            }

            return(InvokeResult.Success);
        }
        /// <summary>
        /// Creates a new profile in the AWS SDK Store for storing credentials in encrypted form.
        /// </summary>
        /// <remarks>
        /// The encrypted credentials in the SDK Store are located in the'%LOCALAPPDATA%\AWSToolkit'
        /// folder in the RegisteredAccounts.json file.
        /// </remarks>
        /// <param name="profileName">Profile name to associate with credentials.</param>
        /// <param name="accessKey">The access key to store with <paramref name="profileName"/>.</param>
        /// <param name="secretKey">The secret key to store with <paramref name="profileName"/>.</param>
        /// <param name="region">The AWS region to associate with <paramref name="profileName"/>.</param>
        /// <returns>Successful or not result.</returns>
        private static bool RegisterAccount(string profileName, string accessKey, string secretKey, string region)
        {
            var chain = new CredentialProfileStoreChain();

            if (chain.ListProfiles().Any(p => p.Name.Equals(profileName,
                                                            StringComparison.InvariantCultureIgnoreCase)))
            {
                MessageBox.Show("The profile name already exists in one or more locations.",
                                Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(false);
            }

            var options = new CredentialProfileOptions
            {
                AccessKey = accessKey,
                SecretKey = secretKey
            };

            var profile    = new CredentialProfile(profileName, options);
            var netSdkFile = new NetSDKCredentialsFile();

            profile.Region = RegionEndpoint.GetBySystemName(region);
            netSdkFile.RegisterProfile(profile);

            MessageBox.Show("AWS account was stored successfully.",
                            Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
            return(true);
        }
Ejemplo n.º 5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddControllersWithViews();
            services.AddIdentity <ApplicationUser, IdentityRole>(options => {
                options.Password.RequireLowercase       = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireDigit           = false;
            })
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            //Navigate users to login page if they are trying to access to authorized page while not logged in
            services.ConfigureApplicationCookie(options => options.LoginPath = "/Home/LogIn");
            //method to register the profile.
            var options = new CredentialProfileOptions
            {
                AccessKey = Configuration.GetConnectionString("AWSAccessKey"),
                SecretKey = Configuration.GetConnectionString("AWSSecretKey"),
            };
            var profile = new CredentialProfile("default", options);

            profile.Region = RegionEndpoint.USEast1;
            var netSDKFile = new NetSDKCredentialsFile();

            netSDKFile.RegisterProfile(profile);
        }
Ejemplo n.º 6
0
        private void btnCreateProfile_Click(object sender, EventArgs e)
        {
            String strProfileName       = txtAWSProfileName.Text.Trim();
            String strAccessKey         = txtAWSAccessKey.Text.Trim();
            String strSecretKey         = txtAWSSecretKey.Text.Trim();
            String strRegionServiceName = GetRegionEndpointServiceName(cboAWSRegions.Text.Trim());

            var AmazonRegionEndpoint = RegionEndpoint.GetBySystemName(strRegionServiceName);

            var AWSProfileOptions = new CredentialProfileOptions
            {
                AccessKey = strAccessKey,
                SecretKey = strSecretKey
            };
            var AWSProfile = new Amazon.Runtime.CredentialManagement.CredentialProfile(strProfileName, AWSProfileOptions);

            AWSProfile.Region = AmazonRegionEndpoint;
            //var AWSCredentialsFile = new Amazon.Runtime.CredentialManagement.SharedCredentialsFile();
            var netSDKFile = new NetSDKCredentialsFile();

            netSDKFile.RegisterProfile(AWSProfile);
            //refreshed the list of available profiles
            GetSavedProfiles();
            GetProfilesToCleanUp();
            //clear Create Profile Fields
            txtAWSProfileName.Text      = "";
            txtAWSAccessKey.Text        = "";
            txtAWSSecretKey.Text        = "";
            cboAWSRegions.Text          = "";
            cboAWSRegions.SelectedIndex = -1;
            btnCreateProfile.Enabled    = false;
        }
Ejemplo n.º 7
0
        public async Task <IActionResult> Apply(LoginModel model)
        {
            DbContextService service = new DbContextService(_appSettings);

            try{
                BaseContext context = service.CreateDbContext(model);
                var         person  = context.Person.Take(1).ToList();

                ViewData["PrimaryConnectionMessage"] = "Primary Connection Test Successful";
                ViewData["PrimaryConnectionError"]   = false;
            }
            catch (Exception ex) {
                ViewData["PrimaryConnectionMessage"] = ex.Message;
                ViewData["PrimaryConnectionError"]   = true;
            }

            if (!String.IsNullOrEmpty(model.ReplicaDatabaseName))
            {
                try{
                    BaseContext context = service.CreateReplicaDbContext(model);
                    var         person  = context.Person.Take(1).ToList();

                    ViewData["ReplicaConnectionMessage"] = "Secondary Connection Test Successful";
                    ViewData["ReplicaConnectionError"]   = false;
                }catch (Exception ex) {
                    ViewData["ReplicaConnectionMessage"] = ex.Message;
                    ViewData["ReplicaConnectionError"]   = true;
                }
            }

            if (!String.IsNullOrEmpty(model.ReplicationTaskArn) && !String.IsNullOrEmpty(model.AccessKey) && !String.IsNullOrEmpty(model.SecretKey) && !String.IsNullOrEmpty(model.EndPointArn))
            {
                try{
                    NetSDKCredentialsFile    credentialsFile = new NetSDKCredentialsFile();
                    CredentialProfileOptions options         = new CredentialProfileOptions();
                    options.AccessKey = model.AccessKey;
                    options.SecretKey = model.SecretKey;
                    credentialsFile.RegisterProfile(new CredentialProfile("default", options));

                    TestConnectionRequest request = new TestConnectionRequest();
                    request.ReplicationInstanceArn = model.ReplicationTaskArn;
                    request.EndpointArn            = model.EndPointArn;

                    var statistics = await _migrationService.TestConnectionAsync(request);

                    ViewData["AWSConnectionMessage"] = "AWS API Connection Test Successful";
                    ViewData["AWSConnectionError"]   = false;
                }
                catch (Exception ex) {
                    ViewData["AWSConnectionMessage"] = ex.Message;
                    ViewData["AWSConnectionError"]   = true;
                }
            }

            return(Index(model));
        }
Ejemplo n.º 8
0
        private void Authenticate()
        {
            CredentialProfileOptions options = new CredentialProfileOptions()
            {
                AccessKey = _accesKey, SecretKey = _secretKey
            };

            CredentialProfile profile = new CredentialProfile("basic_profile", options);
            var netSDKFile            = new NetSDKCredentialsFile();

            netSDKFile.RegisterProfile(profile);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// IMPORTANT:
        /// This creates an AWS user profile entry in the file located in this
        /// folder: C:\Users\<username>\AppData\Local\AWSToolkit\RegisteredAccounts.json
        ///
        /// See reference at https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-creds.html
        ///
        /// This is done for expediency, experiment and example purposes. For real production functionality you do
        /// not want to expose your credentials in this manner. For security and credential file concerns
        /// see this reference: https://docs.aws.amazon.com/sdk-for-net/v2/developer-guide/net-dg-config-creds.html#creds-assign
        ///
        /// </summary>
        private static void CreateProfile()
        {
            var options = new CredentialProfileOptions
            {
                AccessKey = "add-user-key-here",
                SecretKey = "add-user-secret-here"
            };
            var profile = new Amazon.Runtime.CredentialManagement.CredentialProfile("basic_profile", options);

            profile.Region = awsRegion;
            var netSDKFile = new NetSDKCredentialsFile();

            netSDKFile.RegisterProfile(profile);
        }
Ejemplo n.º 10
0
        public AWSHelper()
        {
            var options = new CredentialProfileOptions
            {
                AccessKey = "",
                SecretKey = ""
            };
            var profile = new Amazon.Runtime.CredentialManagement.CredentialProfile("basic_profile", options);

            profile.Region = RegionEndpoint.USWest1;
            var netSDKFile = new NetSDKCredentialsFile();

            netSDKFile.RegisterProfile(profile);
        }
Ejemplo n.º 11
0
        // dotnet test --filter "FullyQualifiedName=damper_dan_client.tests.AWSTests.UploadToS3Bucket"
        public void UploadToS3Bucket()
        {
            Console.WriteLine("UploadToS3Bucket");
            var options = new CredentialProfileOptions {
                AccessKey = "AKIAJETN6IOF34SLVHTQ",
                SecretKey = "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"
            };
            var profile = new Amazon.Runtime.CredentialManagement.CredentialProfile("basic_profile", options);

            profile.Region = RegionEndpoint.USEast1;
            var netSDKFile = new NetSDKCredentialsFile();

            netSDKFile.RegisterProfile(profile);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Sets credentials for AmazonCloudWatchLogsClient
        /// </summary>
        private void ConfigureCredentials()
        {
            var options = new CredentialProfileOptions {
                AccessKey = "access_key", SecretKey = "secret_key"
            };                                                                                                 // TODO: These would go into appsettings.json

            var profile = new Amazon.Runtime.CredentialManagement.CredentialProfile("basic_profile", options);

            profile.Region = RegionEndpoint.USEast2;

            var netSdkFile = new NetSDKCredentialsFile();

            netSdkFile.RegisterProfile(profile);
        }
Ejemplo n.º 13
0
        private static void RegisterProfileFromUser(NetSDKCredentialsFile credentialsFile = null)
        {
            credentialsFile ??= new NetSDKCredentialsFile();

            Console.Write("Access Key>");
            var accessKey = Console.ReadLine();

            Console.Write("Secret Key>");
            var secretKey = Console.ReadLine();

            RegionEndpoint region;

            var regions = RegionEndpoint.EnumerableAllRegions.OrderBy(r => r.SystemName).ToList();

            for (int i = 0; i < regions.Count; i++)
            {
                Console.WriteLine($"{i}) {regions[i]}");
            }

            Console.Write("Region>");
            while (true)
            {
                var line = Console.ReadLine();
                if (int.TryParse(line, out var index) && index >= 0 && index < regions.Count)
                {
                    region = regions[index];
                    break;
                }

                var blank = new string(' ', line.Length);
                Console.SetCursorPosition("Region>".Length, Console.CursorTop - 1);
                Console.Write(blank);
                Console.SetCursorPosition("Region>".Length, Console.CursorTop);
            }

            var options = new CredentialProfileOptions
            {
                AccessKey = accessKey,
                SecretKey = secretKey
            };

            var profile = new CredentialProfile(_defaultProfile, options)
            {
                Region = region
            };

            credentialsFile.RegisterProfile(profile);
        }
Ejemplo n.º 14
0
        public CredentialProfile RegisterAwsProfile(string profileName, string accessKey, string secretKey, RegionEndpoint region)
        {
            var profile = new CredentialProfile(profileName, new CredentialProfileOptions
            {
                AccessKey = accessKey,
                SecretKey = secretKey,
            });

            profile.Region = region;

            var credentialFile = new NetSDKCredentialsFile();

            credentialFile.RegisterProfile(profile);

            return(profile);
        }
Ejemplo n.º 15
0
        static void InitializeProfile()
        {
            var options = new CredentialProfileOptions
            {
                AccessKey = "33",
                SecretKey = "444+Puwxq+"
            };

            var profile = new CredentialProfile("basic_profile", options)
            {
                Region = RegionEndpoint.APSoutheast2
            };

            var netSDKFile = new NetSDKCredentialsFile();

            netSDKFile.RegisterProfile(profile);
        }
Ejemplo n.º 16
0
        private AmazonS3Client GetS3Client()
        {
            var options = new CredentialProfileOptions
            {
                AccessKey = System.Environment.GetEnvironmentVariable("AWSACCESSKEY"),
                SecretKey = System.Environment.GetEnvironmentVariable("AWSSECRET")
            };


            var profile    = new Amazon.Runtime.CredentialManagement.CredentialProfile("basic_profile", options);
            var netSDKFile = new NetSDKCredentialsFile();

            netSDKFile.RegisterProfile(profile);

            var creds = AWSCredentialsFactory.GetAWSCredentials(profile, netSDKFile);

            return(new AmazonS3Client(creds, RegionEndpoint.USEast1));
        }
Ejemplo n.º 17
0
        public AwsEc2(ShadowsocksController controller, string accessKey, string secretKey)
        {
            // aws 配置用户名和密码
            AddOrUpdateAppSettings("AWSProfileName", "aws_profile");
            var options = new CredentialProfileOptions
            {
                AccessKey = accessKey,
                SecretKey = secretKey
            };
            var profile    = new Amazon.Runtime.CredentialManagement.CredentialProfile("aws_profile", options);
            var netSDKFile = new NetSDKCredentialsFile();

            netSDKFile.RegisterProfile(profile);

            // 初始化客户端
            ec2Client       = new AmazonEC2Client(RegionEndpoint.USWest2);
            this.controller = controller;
        }
Ejemplo n.º 18
0
        public override void Execute()
        {
            var options = new CredentialProfileOptions
            {
                AccessKey = AccessKey,
                SecretKey = SecretKey
            };

            var profile = new CredentialProfile(ProfileName, options)
            {
                Region = RegionEndpoint.GetBySystemName(Region)
            };

            var netSDKFile = new NetSDKCredentialsFile();

            netSDKFile.RegisterProfile(profile);

            Console.WriteLine($"*** Completed registration for AWS credential profile as named '{ProfileName}' on SDK Store.");
        }
Ejemplo n.º 19
0
        private AWSCredentials GetCredentials()
        {
            const string profileName     = "example_profile";
            const string endpointName    = profileName + "_endpoint";
            const string samlEndpointUrl = "https://<adfs host>/adfs/ls/IdpInitiatedSignOn.aspx?loginToRp=urn:amazon:webservices";

            //Create and register our saml endpoint that will be used by our profile
            var endpoint = new SAMLEndpoint(
                endpointName,
                new Uri(samlEndpointUrl),
                SAMLAuthenticationType.Negotiate);

            var endpointManager = new SAMLEndpointManager();

            endpointManager.RegisterEndpoint(endpoint);

            //Use the default credential file.  This could be substituted for a targeted file.
            var netSdkFile = new NetSDKCredentialsFile();

            CredentialProfile profile;

            //See if we already have the profile and create it if not
            if (netSdkFile.TryGetProfile(profileName, out profile).Equals(false))
            {
                var profileOptions = new CredentialProfileOptions
                {
                    EndpointName = endpointName,

                    //This was kind of confusing as the AWS documentation did not say that this was
                    //a comma separated string combining the principle ARN (the ARN of the identity provider)
                    //and the ARN of the role.  The documentation only shows that it's the ARN of the role.
                    RoleArn = principleArn + "," + roleArn
                };

                profile        = new CredentialProfile(profileName, profileOptions);
                profile.Region = RegionEndpoint.USEast1;

                //Store the profile
                netSdkFile.RegisterProfile(profile);
            }

            return(AWSCredentialsFactory.GetAWSCredentials(profile, netSdkFile));
        }
Ejemplo n.º 20
0
 public string RegistrarCredenciais()
 {  //Apenas para desenvolver
     try
     {
         var options = new CredentialProfileOptions
         {
             AccessKey = "",
             SecretKey = ""
         };
         var profile = new Amazon.Runtime.CredentialManagement.CredentialProfile("root_profile", options);
         profile.Region = RegionEndpoint.SAEast1;
         var netSDKFile = new NetSDKCredentialsFile();
         netSDKFile.RegisterProfile(profile);
         return("Registrado");
     }
     catch (Exception e)
     {
         return("Erro" + e.Message);
     }
 }
Ejemplo n.º 21
0
        public void subeFile()
        {
            //_environment = environment;
            AmazonS3Config cfg = new AmazonS3Config();

            cfg.RegionEndpoint = bucketRegion;
            var options = new CredentialProfileOptions
            {
                AccessKey = "",
                SecretKey = ""
            };
            var profile = new CredentialProfile("basic_profile", options);

            profile.Region = RegionEndpoint.USEast1;
            var netSDKFile = new NetSDKCredentialsFile();

            netSDKFile.RegisterProfile(profile);
            s3Client = new AmazonS3Client("", "", RegionEndpoint.EUWest2);
            UploadFileAsync().Wait();
        }
Ejemplo n.º 22
0
        private static AWSCredentials GetAwsCredentials()
        {
            var isLocal = string.IsNullOrEmpty(Environment.GetEnvironmentVariable("WEBSITE_INSTANCE_ID"));

            Log.LogInformation($"is local: {isLocal}");
            var options = new CredentialProfileOptions
            {
                AccessKey = Environment.GetEnvironmentVariable(isLocal ? "PlainUsername" : "UsernameFromKeyVault", EnvironmentVariableTarget.Process),
                SecretKey = Environment.GetEnvironmentVariable(isLocal ? "PlainPassword" : "PasswordFromKeyVault", EnvironmentVariableTarget.Process)
            };
            var profile = new CredentialProfile("s3_reader", options);

            profile.Region = RegionEndpoint.EUCentral1;
            var netSDKFile = new NetSDKCredentialsFile();

            netSDKFile.RegisterProfile(profile);

            Log.LogInformation($"Calling GetAWSCredentials for profile '{profile.Name}', AccessKey '{profile.Options.AccessKey}'");
            AWSCredentials awsCredentials = AWSCredentialsFactory.GetAWSCredentials(profile, netSDKFile, true);

            Log.LogInformation("Got AWS Credentials");
            return(awsCredentials);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// プロファイルにキーを保存。
        /// </summary>
        /// <returns>True:成功 False:失敗</returns>
        private bool save_config()
        {
            if (string.IsNullOrEmpty(Txt_AWS_AccessKey.Text) || string.IsNullOrEmpty(Txt_AWS_SecretKey.Text))
            {
                return(false);
            }
            else
            {
                //プロファイル設定に保存
                // 参考:http://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-creds.html

                var profile_options = new CredentialProfileOptions();
                profile_options.AccessKey = Txt_AWS_AccessKey.Text;
                profile_options.SecretKey = Txt_AWS_SecretKey.Text;

                var profile = new CredentialProfile(this.aws_credential_profile_name, profile_options);
                profile.Region = Amazon.RegionEndpoint.APNortheast1; //東京リージョン
                var netSDKFile = new NetSDKCredentialsFile();
                netSDKFile.RegisterProfile(profile);

                return(true);
            }
        }
        // GET: Player
        public async Task <IActionResult> ReplicationStatistics()
        {
            NetSDKCredentialsFile    credentialsFile = new NetSDKCredentialsFile();
            CredentialProfileOptions options         = new CredentialProfileOptions();

            options.AccessKey = HttpContext.Session.GetString("AccessKey");
            options.SecretKey = HttpContext.Session.GetString("SecretKey");
            credentialsFile.RegisterProfile(new CredentialProfile("default", options));

            DescribeTableStatisticsRequest request = new DescribeTableStatisticsRequest();

            request.ReplicationTaskArn = HttpContext.Session.GetString("ReplicationTaskArn");

            var statistics = await DbMigrationService.DescribeTableStatisticsAsync(request);

            List <DisplayTableStatistics> tableStatistics = new List <DisplayTableStatistics>();

            foreach (TableStatistics stat in statistics.TableStatistics)
            {
                tableStatistics.Add(new DisplayTableStatistics(stat, displayIcon(stat.TableName), statusColor(stat)));
            }

            return(View(tableStatistics));
        }
Ejemplo n.º 25
0
        /*
         * This method reads the polly properties and the ready-made AWS Profile to send a polly request.
         * It returns the Stream of the MP3 created.
         *
         * This method will likely fail in three ways:
         * 1) The Profile is bad
         * 2) The user is offline
         * 3) The specified content for the request is faulty
         *
         * I tried to address the 3) with value checks in the frontend, the others are not checked for at the moment.
         */
        private Stream MakeAwsCall(PollyProperties pollyProps)
        {
            // Store the Amazon Profile in the Credentials Engine for later use
            var netSdkFile = new NetSDKCredentialsFile();

            netSdkFile.RegisterProfile(_awsProfile);

            // This chain uses the credentials to create a token for usage,
            // Later the token is used in the Credentials
            // The chain stores it into awsCredentials, that is used for the client.
            var            chain = new CredentialProfileStoreChain();
            AWSCredentials awsCredentials;
            Stream         audioStream = null;

            // use awsCredentials
            if (chain.TryGetAWSCredentials("polly_profile", out awsCredentials))
            {
                using (var client = new AmazonPollyClient(awsCredentials, _awsProfile.Region))
                {
                    var response = client.SynthesizeSpeechAsync(new SynthesizeSpeechRequest
                    {
                        OutputFormat = "mp3",
                        SampleRate   = pollyProps.SamplingRate.ToString(),
                        Text         = pollyProps.TextToPlay,
                        TextType     = "text",
                        VoiceId      = pollyProps.Voice // One of Hans, Jenny , ...
                    });
                    response.Wait();

                    var res = response.Result;
                    audioStream = res.AudioStream;
                }
            }

            return(audioStream);
        }
Ejemplo n.º 26
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Enable CORS.
            services.AddCors();

            // Add MVC service.
            services.AddMvc();

            // Create AWS Profile options for basic profile.
            var awsProfileOptions = new Amazon.Runtime.CredentialManagement.CredentialProfileOptions()
            {
                AccessKey = Configuration.GetValue <string>("Secrets:AWS:AccessKey"),
                SecretKey = Configuration.GetValue <string>("Secrets:AWS:AccessKeySecret"),
            };

            // Creates basic profile with above options, then set AWS region.
            var awsProfile = new Amazon.Runtime.CredentialManagement.CredentialProfile("basic-profile", awsProfileOptions);

            awsProfile.Region = RegionEndpoint.APNortheast2;

            // Registers AWS profile to AWS SDK's .NET SDK credentials file.
            var sdkFile = new NetSDKCredentialsFile();

            sdkFile.RegisterProfile(awsProfile);

            // Add AWS options.
            services.AddDefaultAWSOptions(new AWSOptions()
            {
                Region = RegionEndpoint.APNortheast2, Profile = awsProfile.Name
            });

            // Add DynamoDB service.
            services.AddAWSService <IAmazonDynamoDB>();

            // Add UserServices.
            // If want to use classic user service, use `UserService`.
            services.AddScoped <IUserService, DynamoDBUserService>();

            // Configure JWT authentication.
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false; // NOTE: This should be set to `true` on production.
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(System.Text.Encoding.ASCII.GetBytes(Configuration.GetValue <string>("Secrets:JWT"))),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });

            // In production, the React files will be served from this directory
            // This code portion is not related to webpack_hmr.
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "wwwroot/dist";
            });
        }
Ejemplo n.º 27
0
        public async Task <IActionResult> OnPost()
        {
            var errorMsg = "";

            if (!ModelState.IsValid)
            {
                return(Page());
            }
            // var helper = FileHelper.ProcessFormFile(Upload, ModelState);
            if (!ModelState.IsValid)
            {
                return(Page());
            }
            var guid = Guid.NewGuid();

            NewFileUp.FileUid   = guid.ToString();
            NewFileUp.TimeStamp = DateTime.Now;
            NewFileUp.LastMod   = DateTime.Now;
            _context.FileUp.Add(NewFileUp);
            await _context.SaveChangesAsync();

            //


            /******************************/
            try
            {
                //var f = new ;
                if (FileHelper.GetConfigFromDb(_context))
                {
                    //fileConfigurator
                    // var fs = f.();

                    // var file = Path.Combine(_environment.ContentRootPath, "Data", "Uploads", guid.ToString());
                    var file = Path.Combine(_environment.ContentRootPath, "Data", "Uploads", NewFileUp.FileUid);
                    using (var fileStream = new FileStream(file, FileMode.Create))
                    {
                        await Upload.CopyToAsync(fileStream);
                    }
                    var options = new CredentialProfileOptions
                    {
                        AccessKey = FileHelper.getFileConfigAccessKey(),
                        SecretKey = FileHelper.getFileConfigSecretKey()
                    };
                    var profile = new CredentialProfile("basic_profile", options);
                    profile.Region = RegionEndpoint.USWest2;
                    var netSDKFile = new NetSDKCredentialsFile();
                    netSDKFile.RegisterProfile(profile);
                    /// crear la solicitud para subir el archivo
                    /// recibe 3 parámetros:
                    /// 1. BucketName: el nombre del bucket
                    /// 2. Key: el nombre del archivo, es como se quiere llamar, incluso con ruta relativa. Ejemplo: directorio/archivo.txt
                    /// 3. FilePath: ruta física del archivo a subir
                    PutObjectRequest request = new PutObjectRequest()
                    {
                        BucketName = FileHelper.getFileConfigBucketName(),
                        Key        = NewFileUp.FileUid,
                        FilePath   = file //FileHelper.getFileConfigFilePath()
                    };
                    //asadasdasdsadsa
                    AmazonS3Client    client   = new AmazonS3Client(RegionEndpoint.USWest2);
                    PutObjectResponse response = await client.PutObjectAsync(request);
                }
            }
            catch (AmazonS3Exception amazonS3Exception)
            {
                if (amazonS3Exception.ErrorCode != null &&
                    (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
                     ||
                     amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
                {
                    errorMsg = "Check the provided AWS Credentials.For service sign up go to http://aws.amazon.com/s3";
                }
                else if (amazonS3Exception.ErrorCode.Equals("PermanentRedirect"))
                {
                    errorMsg = amazonS3Exception.Message;
                }
                else
                {
                    errorMsg = "Error occurred. Message:" + amazonS3Exception.Message + " when writing an object";
                }
            }
            catch (Exception ex)
            {
                errorMsg = ex.Message;
            }
            finally
            {
                RedirectToPage("/Error", new { errorMsg });
            }
            /******************************/
            return(RedirectToPage("/FileUploaders/Files/Index"));
        }
Ejemplo n.º 28
0
        public Solicitudes GetTestAsync(List <Tab_ConfigSys> Tab_ConfigSys, Solicitudes sol)
        {
            string xClase   = string.Format("{0}|{1}", MethodBase.GetCurrentMethod().Module.Name, MethodBase.GetCurrentMethod().DeclaringType.Name);
            string xProceso = MethodBase.GetCurrentMethod().Name;

            var dto_excepcion = new UTL_TRA_EXCEPCION
            {
                STR_CLASE      = xClase,
                STR_EVENTO     = xProceso,
                STR_PARAMETROS = JsonConvert.SerializeObject(sol),
                STR_APLICATIVO = ConfigurationManager.AppSettings["APLICATIVO"].ToString(),
                STR_SERVIDOR   = System.Net.Dns.GetHostName(),
                FEC_CREACION   = DateTime.Now
            };
            Solicitudes _Solicitudes = new Solicitudes();

            var options = new CredentialProfileOptions
            {
                AccessKey = Tab_ConfigSys[0].llave_Config1,
                SecretKey = Tab_ConfigSys[0].llave_Config2
            };

            try
            {
                var profile = new Amazon.Runtime.CredentialManagement.CredentialProfile("AWSProfileName", options);
                profile.Region = RegionEndpoint.USWest1;
                var netSDKFile = new NetSDKCredentialsFile();
                netSDKFile.RegisterProfile(profile);

                float similarityThreshold = 70F;
                //String sourceImage = sol.arrImageSelfie;
                //String targetImage = sol.UrlFotoCedula;

                //using (AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient(Tab_ConfigSys[0].llave_Config1, Tab_ConfigSys[0].llave_Config2, RegionEndpoint.USWest1))
                using (AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient(Tab_ConfigSys[0].llave_Config1, Tab_ConfigSys[0].llave_Config2))
                {
                    Amazon.Rekognition.Model.Image imageSource = new Amazon.Rekognition.Model.Image();

                    //using (FileStream fs = new FileStream(new MemoryStream(bytes), FileMode.Open, FileAccess.Read))
                    //{
                    // byte[] data = new byte[fs.Length];
                    //  fs.Read(data, 0, (int)fs.Length);
                    imageSource.Bytes = new MemoryStream(sol.arrImageSelfie);
                    // }


                    Amazon.Rekognition.Model.Image imageTarget = new Amazon.Rekognition.Model.Image();

                    // using (FileStream fs = new FileStream(targetImage, FileMode.Open, FileAccess.Read))
                    //{
                    //  byte[] data = new byte[fs.Length];
                    //  data = new byte[fs.Length];
                    //  fs.Read(data, 0, (int)fs.Length);
                    imageTarget.Bytes = new MemoryStream(sol.arrImageCedulaFrontal);
                    // }


                    CompareFacesRequest compareFacesRequest = new CompareFacesRequest()
                    {
                        SourceImage         = imageSource,
                        TargetImage         = imageTarget,
                        SimilarityThreshold = similarityThreshold
                    };

                    // Call operation
                    CompareFacesResponse compareFacesResponse = rekognitionClient.CompareFaces(compareFacesRequest);

                    // Display results
                    //foreach (CompareFacesMatch match in compareFacesResponse.FaceMatches)
                    compareFacesResponse.FaceMatches.ForEach(match =>
                    {
                        ComparedFace face = match.Face;

                        BoundingBox position = face.BoundingBox;

                        _Solicitudes.PorcentMatched = face.Confidence;
                        _Solicitudes.PositionLeft   = position.Left;
                        _Solicitudes.PositionTop    = position.Top;
                    });

                    _Solicitudes.IdTipoIdentificacion = sol.IdTipoIdentificacion;
                    _Solicitudes.Identificacion       = sol.Identificacion;

                    if (_Solicitudes.PorcentMatched == 0 || _Solicitudes.PorcentMatched == null)
                    {
                        _Solicitudes.UnMatchedFace = compareFacesResponse.UnmatchedFaces[0].Confidence;
                    }
                    else
                    {
                        _Solicitudes.UnMatchedFace = 0;
                    }
                    _Solicitudes.ImageRotationSource = compareFacesResponse.SourceImageOrientationCorrection;
                    _Solicitudes.ImageRotationTarget = compareFacesResponse.TargetImageOrientationCorrection;
                }
                return(_Solicitudes);
            }
            catch (Exception ex)
            {
                dto_excepcion.STR_MENSAJE = ex.Message;
                dto_excepcion.IS_TELEGRAM = true;
                TwoFunTwoMe_DataAccess.Utility.guardaExcepcion(dto_excepcion, ConfigurationManager.ConnectionStrings["TwoFunTwoMeConnection"].ConnectionString);
                _Solicitudes.Mensaje = "ERR_imageTarget";
                throw;
            }
        }
Ejemplo n.º 29
0
        public Solicitudes DetectText(List <Tab_ConfigSys> Tab_ConfigSys, byte[] bytes, string Identificacion, int IdTipoIdentificacion, int?OPC)
        {
            string xClase   = string.Format("{0}|{1}", MethodBase.GetCurrentMethod().Module.Name, MethodBase.GetCurrentMethod().DeclaringType.Name);
            string xProceso = MethodBase.GetCurrentMethod().Name;

            bool resp  = false;
            var  param = new
            {
                UriFoto            = bytes,
                TipoIdentificacion = IdTipoIdentificacion,
                cedula             = Identificacion,
                OPCe = OPC
            };
            var dto_excepcion = new UTL_TRA_EXCEPCION
            {
                STR_CLASE      = xClase,
                STR_EVENTO     = xProceso,
                FEC_CREACION   = DateTime.Now,
                STR_PARAMETROS = JsonConvert.SerializeObject(param),
                STR_SERVIDOR   = System.Net.Dns.GetHostName(),
                STR_APLICATIVO = ConfigurationManager.AppSettings["APLICATIVO"].ToString()
            };
            Solicitudes _Solicitudes = new Solicitudes();

            _Solicitudes.Identificacion = Identificacion;
            ManagerSolcitudes managerSolcitudes = new ManagerSolcitudes();
            var FecVencCedula = managerSolcitudes.ConsultaFechaVencimientoCedula(_Solicitudes);

            var options = new CredentialProfileOptions
            {
                AccessKey = Tab_ConfigSys[0].llave_Config1,
                SecretKey = Tab_ConfigSys[0].llave_Config2
            };

            try
            {
                var profile = new Amazon.Runtime.CredentialManagement.CredentialProfile("AWSProfileName", options);
                profile.Region = RegionEndpoint.USWest1;
                var netSDKFile = new NetSDKCredentialsFile();
                netSDKFile.RegisterProfile(profile);

                using (AmazonRekognitionClient rekoClient = new AmazonRekognitionClient(Tab_ConfigSys[0].llave_Config1, Tab_ConfigSys[0].llave_Config2, RegionEndpoint.USEast1))
                {
                    Amazon.Rekognition.Model.Image img = new Amazon.Rekognition.Model.Image();

                    img.Bytes = new MemoryStream(bytes);

                    DetectTextRequest dfr = new DetectTextRequest();

                    dfr.Image = img;
                    var  outcome = rekoClient.DetectText(dfr);
                    bool dia     = false;
                    bool mes     = false;
                    bool anio    = false;
                    foreach (var texto in outcome.TextDetections)
                    {
                        string cedula = "";

                        cedula = texto.DetectedText;
                        cedula = cedula.Replace(" ", "").Trim();


                        var cedresp   = cedula.Split(':');
                        var respuesta = cedresp.Where(x => x.ToString().Equals(Identificacion) || cedula.Equals(Identificacion)).Any();
                        if (respuesta)
                        {
                            resp = respuesta;
                        }
                        if (FecVencCedula != null)
                        {
                            var resDia = cedresp.Where(x => x.ToString().Equals(Convert.ToString(FecVencCedula.Dia)) || cedula.Equals(Convert.ToString(FecVencCedula.Dia))).Any();
                            if (resDia)
                            {
                                dia = resDia;
                            }
                            var resMes = cedresp.Where(x => x.ToString().Equals(Convert.ToString(FecVencCedula.Mes)) || cedula.Equals(Convert.ToString(FecVencCedula.Mes))).Any();
                            if (resMes)
                            {
                                mes = resMes;
                            }
                            var resAnio = cedresp.Where(x => x.ToString().Equals(Convert.ToString(FecVencCedula.Anio)) || cedula.Equals(Convert.ToString(FecVencCedula.Anio))).Any();
                            if (resAnio)
                            {
                                anio = resAnio;
                            }

                            if (respuesta == true && dia == true && mes == true && anio == true)
                            {
                                break;
                            }
                        }
                        else
                        {
                            if (respuesta)
                            {
                                break;
                            }
                        }
                    }
                    var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(outcome.TextDetections.Select(x => x.DetectedText));


                    _Solicitudes.Result       = resp;
                    _Solicitudes.Dia          = Convert.ToInt32(dia);
                    _Solicitudes.Mes          = Convert.ToInt32(mes);
                    _Solicitudes.Anio         = Convert.ToInt32(anio);
                    _Solicitudes.DetectedText = jsonString;
                }
                //return outcome.TextDetections.Select(x => x.DetectedText).ToList();
                return(_Solicitudes);
            }
            catch (Exception ex)
            {
                dto_excepcion.STR_MENSAJE = ex.Message;
                dto_excepcion.IS_TELEGRAM = true;
                TwoFunTwoMe_DataAccess.Utility.guardaExcepcion(dto_excepcion, ConfigurationManager.ConnectionStrings["TwoFunTwoMeConnection"].ConnectionString);
                _Solicitudes.Mensaje = "ERR_Detect Text";
                throw;
            }
        }
        public static void DoImageRecognition(string path)
        {
            if (File.Exists(path))
            {
                var options = new CredentialProfileOptions()
                {
                    AccessKey = "",
                    SecretKey = ""
                };

                var profile = new CredentialProfile("test", options)
                {
                    Region = RegionEndpoint.USEast2
                };
                var netSdkFile = new NetSDKCredentialsFile();
                netSdkFile.RegisterProfile(profile);


                AmazonRekognitionClient rekoClient = new AmazonRekognitionClient(RegionEndpoint.USEast2);
                MemoryStream            mStream;

                using (System.Drawing.Image image = System.Drawing.Image.FromFile($"{path}"))
                {
                    using (MemoryStream m = new MemoryStream())
                    {
                        image.Save(m, image.RawFormat);
                        mStream = m;
                    }
                }

                DetectTextRequest detectTextRequest = new DetectTextRequest()
                {
                    Image = new Image()
                    {
                        Bytes = mStream
                    }
                };

                try
                {
                    _stopwatch.Start();
                    DetectTextResponse detectTextResponse = rekoClient.DetectText(detectTextRequest);
                    foreach (TextDetection text in detectTextResponse.TextDetections)
                    {
                        CheckFoundSerial(text.DetectedText);
                    }

                    Console.WriteLine($"Query time {_stopwatch.ElapsedMilliseconds}ms");
                    if (foundSerial)
                    {
                        Console.WriteLine($"Serial number: {serialNumber}");
                    }
                    else
                    {
                        Console.WriteLine("Could not find any serial number");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }

            _stopwatch.Reset();
            Console.WriteLine();
            Console.WriteLine("Press enter to show menu");
            Console.ReadKey();
            Console.Clear();
            Console.WriteLine("Press 0 for image processing using camera or 1-9 for stored images");
        }