예제 #1
0
        private async Task RunRequest(WebsiteConfiguration configuration, Channel <Response> channel, CancellationToken token)
        {
            var client    = clientFactory.CreateClient(configuration.Url);
            var stopwatch = Stopwatch.StartNew();
            var writer    = channel.Writer;

            while (!token.IsCancellationRequested)
            {
                stopwatch.Restart();
                try
                {
                    var request  = new HttpRequestMessage(HttpMethod.Get, configuration.Url);
                    var response = await client.SendAsync(request, token);

                    await writer.WriteAsync(new Response
                    {
                        Success = response.IsSuccessStatusCode,
                        Time    = stopwatch.Elapsed,
                    });
                }
                catch (Exception ex)
                {
                    await writer.WriteAsync(new Response
                    {
                        Success   = false,
                        Time      = stopwatch.Elapsed,
                        Exception = ex,
                    });
                }
            }
        }
        public UsersService(ApplicationDbContext dbContext,
                            IEncrypter encrypter,
                            IUserInfoProvider userInfoProvider,
                            IPolicy <RegisterUserModel> registerUserPolicy,
                            IPolicy <RegisterDomainUserModel> registerDomainUserPolicy,
                            IPolicy <UpdateUserModel> updateUserPolicy,
                            IPolicy <PasswordResetRequestModel> requestPasswordResetPolicy,
                            IPolicy <ResetPasswordModel> resetPasswordPolicy,
                            IPolicy <PasswordModel> passwordPolicy,
                            ICommsService commsService,
                            IConfigurationRoot configurationRoot)
        {
            this.dbContext                  = dbContext;
            this.encrypter                  = encrypter;
            this.userInfoProvider           = userInfoProvider;
            this.registerUserPolicy         = registerUserPolicy;
            this.registerDomainUserPolicy   = registerDomainUserPolicy;
            this.updateUserPolicy           = updateUserPolicy;
            this.requestPasswordResetPolicy = requestPasswordResetPolicy;
            this.passwordPolicy             = passwordPolicy;
            this.resetPasswordPolicy        = resetPasswordPolicy;
            this.commsService               = commsService;
            this.configurationRoot          = configurationRoot;
            this.websiteConfiguration       = new WebsiteConfiguration();

            configurationRoot.GetSection("WebsiteConfiguration").Bind(websiteConfiguration);
        }
예제 #3
0
 public DonationService(IRepository <Donation> donationRepository, ILogger logger, IMailer mailer, IOptions <WebsiteConfiguration> config)
 {
     _donationRepository = donationRepository;
     _logger             = logger;
     _mailer             = mailer;
     _config             = config.Value;
     _urlHelper          = new UrlHelper(HttpContext.Current.Request.RequestContext);
 }
예제 #4
0
 public SupportController(ILogger logger, IDataSetsHelper dataSetsHelper, IRoles roles, IMailer mailer, IOptions <WebsiteConfiguration> config, IAuthentication authentication, IFileSourceHelper fileSourceHelper, IStripeService stripeService, IOptions <StripeConfiguration> stripeConfig, IDonationService donationService)
     : base(logger, dataSetsHelper, roles, authentication, fileSourceHelper)
 {
     _logger          = logger;
     _mailer          = mailer;
     _stripeService   = stripeService;
     _donationService = donationService;
     _stripeConfig    = stripeConfig.Value;
     _config          = config.Value;
 }
예제 #5
0
 public ConsultationService(IRepository <Consultation> consultationRepository, ILogger logger, IMailer mailer, IOptions <WebsiteConfiguration> config, IAuthentication authentication, IRepository <UserConsultation> userConsultationRepository)
 {
     _consultationRepository = consultationRepository;
     _logger                     = logger;
     _mailer                     = mailer;
     _authentication             = authentication;
     _userConsultationRepository = userConsultationRepository;
     _config                     = config.Value;
     _urlHelper                  = new UrlHelper(HttpContext.Current.Request.RequestContext);
 }
예제 #6
0
 public UserService(IRepository <User> usersRepository, IRepository <PromoCode> promoCodesRepository, IRepository <UserPromoCode> userPromoCodeRepository, IAuthentication authentication, IMailer mailer, IOptions <WebsiteConfiguration> config, IContactService contactService)
 {
     _usersRepository         = usersRepository;
     _promoCodesRepository    = promoCodesRepository;
     _userPromoCodeRepository = userPromoCodeRepository;
     _authentication          = authentication;
     _mailer         = mailer;
     _contactService = contactService;
     _config         = config.Value;
     _urlHelper      = new UrlHelper(HttpContext.Current.Request.RequestContext);
 }
예제 #7
0
 public SupportController(ILogger logger, IDataSetsHelper dataSetsHelper, IRoles roles, IMailer mailer, IOptions <WebsiteConfiguration> config, IAuthentication authentication, IFileSourceHelper fileSourceHelper, IOptions <StripeConfiguration> stripeConfig, IDonationService donationService, IMembershipService membershipService, IContactService contactService, IOptions <RecaptchaConfiguration> recaptchaConfig, IRecaptchaService recaptchaService)
     : base(logger, dataSetsHelper, roles, authentication, fileSourceHelper, membershipService)
 {
     _logger           = logger;
     _mailer           = mailer;
     _donationService  = donationService;
     _contactService   = contactService;
     _recaptchaService = recaptchaService;
     _recaptchaConfig  = recaptchaConfig.Value;
     _config           = config.Value;
     _urlHelper        = new UrlHelper(System.Web.HttpContext.Current.Request.RequestContext);
 }
예제 #8
0
        internal WebsiteStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            var config = new WebsiteConfiguration()
            {
                DomainName = "hello.awsdevfi.nortal.com",
                Resource   = "./resources/website"
            };

            var resource = new StaticWebsite(this);

            resource.Construct(config);
        }
예제 #9
0
        public void Construct(WebsiteConfiguration app)
        {
            var bucket = new Bucket(this.stack, "WebsiteBucket", new BucketProps {
                BucketName           = app.DomainName,
                PublicReadAccess     = true,
                RemovalPolicy        = RemovalPolicy.DESTROY,
                WebsiteIndexDocument = "index.html"
            });

            var deploy = new BucketDeployment(this.stack, "BucketDeployment", new BucketDeploymentProps {
                DestinationBucket = bucket,
                Sources           = new [] { Source.Asset(app.Resource) }
            });
        }
예제 #10
0
 public MembershipService(ILogger logger, IAuthentication authentication, IRepository <MembershipOption> membershipOptionRepository, IRepository <UserMembership> userMembershipRepository, IRepository <UserCreditPack> userCreditPacksRepository, IRepository <User> usersRepository, IContactService contactService, IMailer mailer, IOptions <WebsiteConfiguration> config, IRepository <PromoCode> promoCodesRepository, IRepository <UserConsultation> userConsultationsRepository)
 {
     _logger                      = logger;
     _authentication              = authentication;
     _membershipOptionRepository  = membershipOptionRepository;
     _userMembershipRepository    = userMembershipRepository;
     _userCreditPacksRepository   = userCreditPacksRepository;
     _usersRepository             = usersRepository;
     _contactService              = contactService;
     _mailer                      = mailer;
     _promoCodesRepository        = promoCodesRepository;
     _userConsultationsRepository = userConsultationsRepository;
     _config                      = config.Value;
     _urlHelper                   = new UrlHelper(HttpContext.Current.Request.RequestContext);
 }
예제 #11
0
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
        static async Task <WebsiteConfiguration> BucketReadWebsite(S3Context ctx)
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
        {
            Console.WriteLine("BucketReadWebsite: " + ctx.Request.Bucket);

            WebsiteConfiguration website = new WebsiteConfiguration();

            website.ErrorDocument         = new ErrorDocument("error.html");
            website.IndexDocument         = new IndexDocument("index.html");
            website.RedirectAllRequestsTo = new RedirectAllRequestsTo("localhost", "http");
            website.RoutingRules          = new RoutingRules(
                new List <RoutingRule> {
                new RoutingRule(new Condition("400", "prefix"),
                                new Redirect("localhost", "302", "http", null, null))
            }
                );
            return(website);
        }
예제 #12
0
        private async Task RunRequests(WebsiteConfiguration configuration, CancellationToken token)
        {
            var channel = Channel.CreateUnbounded <Response>(new UnboundedChannelOptions
            {
                SingleReader = true,
            });

            // Create request tasks
            for (int i = 0; i < configuration.NumberOfThreads; i++)
            {
                await Task.Factory.StartNew(() => RunRequest(configuration, channel, token), TaskCreationOptions.LongRunning);
            }

            var reader = channel.Reader;

            while (!token.IsCancellationRequested)
            {
                var numberOfRequests = await GetNumberOfRequestsWithin(TimeSpan.FromSeconds(1), reader);

                _logger.LogInformation($"Number of requests for {configuration.Url}: {numberOfRequests.success} OK, {numberOfRequests.failed} Failed");
            }
        }
예제 #13
0
        private async Task RequestHandler(HttpContext ctx)
        {
            if (ctx == null)
            {
                throw new ArgumentNullException(nameof(ctx));
            }
            DateTime  startTime = DateTime.Now;
            S3Context s3ctx     = null;

            try
            {
                s3ctx = new S3Context(ctx, _BaseDomains, null, (Logging.S3Requests ? Logger : null));
                s3ctx.Response.Headers.Add("x-amz-request-id", s3ctx.Request.RequestId);
                s3ctx.Response.Headers.Add("x-amz-id-2", s3ctx.Request.RequestId);
            }
            catch (Exception e)
            {
                if (Logging.Exceptions)
                {
                    Logger?.Invoke(_Header + "Exception:" + Environment.NewLine + Common.SerializeJson(e, true));
                }

                return;
            }

            bool                    success           = false;
            bool                    exists            = false;
            S3Object                s3obj             = null;
            ObjectMetadata          md                = null;
            AccessControlPolicy     acp               = null;
            LegalHold               legalHold         = null;
            Retention               retention         = null;
            Tagging                 tagging           = null;
            ListAllMyBucketsResult  buckets           = null;
            ListBucketResult        listBucketResult  = null;
            ListVersionsResult      listVersionResult = null;
            LocationConstraint      location          = null;
            BucketLoggingStatus     bucketLogging     = null;
            VersioningConfiguration versionConfig     = null;
            WebsiteConfiguration    wc                = null;
            DeleteMultiple          delMultiple       = null;
            DeleteResult            delResult         = null;

            try
            {
                if (Logging.HttpRequests)
                {
                    Logger?.Invoke(_Header + "HTTP request: " + Environment.NewLine + s3ctx.Http.ToJson(true));
                }

                if (Logging.S3Requests)
                {
                    Logger?.Invoke(_Header + "S3 request: " + Environment.NewLine + s3ctx.Request.ToJson(true));
                }

                if (PreRequestHandler != null)
                {
                    success = await PreRequestHandler(s3ctx).ConfigureAwait(false);

                    if (success)
                    {
                        await s3ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                }

                switch (s3ctx.Request.RequestType)
                {
                    #region Service

                case S3RequestType.ListBuckets:
                    if (Service.ListBuckets != null)
                    {
                        buckets = await Service.ListBuckets(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(buckets)).ConfigureAwait(false);

                        return;
                    }
                    break;

                    #endregion

                    #region Bucket

                case S3RequestType.BucketDelete:
                    if (Bucket.Delete != null)
                    {
                        await Bucket.Delete(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 204;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketDeleteTags:
                    if (Bucket.DeleteTagging != null)
                    {
                        await Bucket.DeleteTagging(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 204;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketDeleteWebsite:
                    if (Bucket.DeleteWebsite != null)
                    {
                        await Bucket.DeleteWebsite(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 204;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketExists:
                    if (Bucket.Exists != null)
                    {
                        exists = await Bucket.Exists(s3ctx).ConfigureAwait(false);

                        if (exists)
                        {
                            ctx.Response.StatusCode  = 200;
                            ctx.Response.ContentType = "text/plain";
                            await ctx.Response.Send().ConfigureAwait(false);
                        }
                        else
                        {
                            ctx.Response.StatusCode  = 404;
                            ctx.Response.ContentType = "text/plain";
                            await ctx.Response.Send().ConfigureAwait(false);
                        }
                        return;
                    }
                    break;

                case S3RequestType.BucketRead:
                    if (Bucket.Read != null)
                    {
                        listBucketResult = await Bucket.Read(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(listBucketResult)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketReadAcl:
                    if (Bucket.ReadAcl != null)
                    {
                        acp = await Bucket.ReadAcl(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(acp)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketReadLocation:
                    if (Bucket.ReadLocation != null)
                    {
                        location = await Bucket.ReadLocation(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(location)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketReadLogging:
                    if (Bucket.ReadLogging != null)
                    {
                        bucketLogging = await Bucket.ReadLogging(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(bucketLogging)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketReadTags:
                    if (Bucket.ReadTagging != null)
                    {
                        tagging = await Bucket.ReadTagging(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(tagging)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketReadVersioning:
                    if (Bucket.ReadVersioning != null)
                    {
                        versionConfig = await Bucket.ReadVersioning(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(versionConfig)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketReadVersions:
                    if (Bucket.ReadVersions != null)
                    {
                        listVersionResult = await Bucket.ReadVersions(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(listVersionResult)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketReadWebsite:
                    if (Bucket.ReadWebsite != null)
                    {
                        wc = await Bucket.ReadWebsite(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(wc)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketWrite:
                    if (Bucket.Write != null)
                    {
                        await Bucket.Write(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketWriteAcl:
                    if (Bucket.WriteAcl != null)
                    {
                        try
                        {
                            acp = Common.DeserializeXml <AccessControlPolicy>(s3ctx.Request.DataAsString);
                        }
                        catch (InvalidOperationException ioe)
                        {
                            ioe.Data.Add("Context", s3ctx);
                            ioe.Data.Add("RequestBody", s3ctx.Request.DataAsString);
                            Logger?.Invoke(_Header + "XML exception: " + Environment.NewLine + Common.SerializeJson(ioe, true));
                            await s3ctx.Response.Send(S3Objects.ErrorCode.MalformedXML).ConfigureAwait(false);

                            return;
                        }

                        await Bucket.WriteAcl(s3ctx, acp).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketWriteLogging:
                    if (Bucket.WriteLogging != null)
                    {
                        try
                        {
                            bucketLogging = Common.DeserializeXml <BucketLoggingStatus>(s3ctx.Request.DataAsString);
                        }
                        catch (InvalidOperationException ioe)
                        {
                            ioe.Data.Add("Context", s3ctx);
                            ioe.Data.Add("RequestBody", s3ctx.Request.DataAsString);
                            Logger?.Invoke(_Header + "XML exception: " + Environment.NewLine + Common.SerializeJson(ioe, true));
                            await s3ctx.Response.Send(S3Objects.ErrorCode.MalformedXML).ConfigureAwait(false);

                            return;
                        }

                        await Bucket.WriteLogging(s3ctx, bucketLogging).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketWriteTags:
                    if (Bucket.WriteTagging != null)
                    {
                        try
                        {
                            tagging = Common.DeserializeXml <Tagging>(s3ctx.Request.DataAsString);
                        }
                        catch (InvalidOperationException ioe)
                        {
                            ioe.Data.Add("Context", s3ctx);
                            ioe.Data.Add("RequestBody", s3ctx.Request.DataAsString);
                            Logger?.Invoke(_Header + "XML exception: " + Environment.NewLine + Common.SerializeJson(ioe, true));
                            await s3ctx.Response.Send(S3Objects.ErrorCode.MalformedXML).ConfigureAwait(false);

                            return;
                        }

                        await Bucket.WriteTagging(s3ctx, tagging).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketWriteVersioning:
                    if (Bucket.WriteVersioning != null)
                    {
                        try
                        {
                            versionConfig = Common.DeserializeXml <VersioningConfiguration>(s3ctx.Request.DataAsString);
                        }
                        catch (InvalidOperationException ioe)
                        {
                            ioe.Data.Add("Context", s3ctx);
                            ioe.Data.Add("RequestBody", s3ctx.Request.DataAsString);
                            Logger?.Invoke(_Header + "XML exception: " + Environment.NewLine + Common.SerializeJson(ioe, true));
                            await s3ctx.Response.Send(S3Objects.ErrorCode.MalformedXML).ConfigureAwait(false);

                            return;
                        }

                        await Bucket.WriteVersioning(s3ctx, versionConfig).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketWriteWebsite:
                    if (Bucket.WriteWebsite != null)
                    {
                        try
                        {
                            wc = Common.DeserializeXml <WebsiteConfiguration>(s3ctx.Request.DataAsString);
                        }
                        catch (InvalidOperationException ioe)
                        {
                            ioe.Data.Add("Context", s3ctx);
                            ioe.Data.Add("RequestBody", s3ctx.Request.DataAsString);
                            Logger?.Invoke(_Header + "XML exception: " + Environment.NewLine + Common.SerializeJson(ioe, true));
                            await s3ctx.Response.Send(S3Objects.ErrorCode.MalformedXML).ConfigureAwait(false);

                            return;
                        }

                        await Bucket.WriteWebsite(s3ctx, wc).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                    #endregion

                    #region Object

                case S3RequestType.ObjectDelete:
                    if (Object.Delete != null)
                    {
                        await Object.Delete(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 204;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectDeleteMultiple:
                    if (Object.DeleteMultiple != null)
                    {
                        try
                        {
                            delMultiple = Common.DeserializeXml <DeleteMultiple>(s3ctx.Request.DataAsString);
                        }
                        catch (InvalidOperationException ioe)
                        {
                            ioe.Data.Add("Context", s3ctx);
                            ioe.Data.Add("RequestBody", s3ctx.Request.DataAsString);
                            Logger?.Invoke(_Header + "XML exception: " + Environment.NewLine + Common.SerializeJson(ioe, true));
                            await s3ctx.Response.Send(S3Objects.ErrorCode.MalformedXML).ConfigureAwait(false);

                            return;
                        }

                        delResult = await Object.DeleteMultiple(s3ctx, delMultiple).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(delResult)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectDeleteTags:
                    if (Object.DeleteTagging != null)
                    {
                        await Object.DeleteTagging(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 204;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectExists:
                    if (Object.Exists != null)
                    {
                        md = await Object.Exists(s3ctx).ConfigureAwait(false);

                        if (md != null)
                        {
                            if (!String.IsNullOrEmpty(md.ETag))
                            {
                                ctx.Response.Headers.Add("ETag", md.ETag);
                            }
                            ctx.Response.Headers.Add("Last-Modified", md.LastModified.ToString());
                            ctx.Response.Headers.Add("x-amz-storage-class", md.StorageClass);
                            ctx.Response.StatusCode    = 200;
                            ctx.Response.ContentLength = md.Size;
                            ctx.Response.ContentType   = md.ContentType;
                            await ctx.Response.Send(md.Size).ConfigureAwait(false);
                        }
                        else
                        {
                            ctx.Response.StatusCode = 404;
                            await ctx.Response.Send().ConfigureAwait(false);
                        }
                        return;
                    }
                    break;

                case S3RequestType.ObjectRead:
                    if (Object.Read != null)
                    {
                        s3obj = await Object.Read(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode    = 200;
                        ctx.Response.ContentType   = s3obj.ContentType;
                        ctx.Response.ContentLength = s3obj.Size;
                        await ctx.Response.Send(s3obj.Size, s3obj.Data).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectReadAcl:
                    if (Object.ReadAcl != null)
                    {
                        acp = await Object.ReadAcl(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(acp)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectReadLegalHold:
                    if (Object.ReadLegalHold != null)
                    {
                        legalHold = await Object.ReadLegalHold(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(legalHold)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectReadRange:
                    if (Object.ReadRange != null)
                    {
                        s3obj = await Object.ReadRange(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode    = 200;
                        ctx.Response.ContentType   = s3obj.ContentType;
                        ctx.Response.ContentLength = s3obj.Size;
                        await ctx.Response.Send(s3obj.Size, s3obj.Data).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectReadRetention:
                    if (Object.ReadRetention != null)
                    {
                        retention = await Object.ReadRetention(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(retention)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectReadTags:
                    if (Object.ReadTagging != null)
                    {
                        tagging = await Object.ReadTagging(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(tagging)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectWrite:
                    if (Object.Write != null)
                    {
                        await Object.Write(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectWriteAcl:
                    if (Object.WriteAcl != null)
                    {
                        try
                        {
                            acp = Common.DeserializeXml <AccessControlPolicy>(s3ctx.Request.DataAsString);
                        }
                        catch (InvalidOperationException ioe)
                        {
                            ioe.Data.Add("Context", s3ctx);
                            ioe.Data.Add("RequestBody", s3ctx.Request.DataAsString);
                            Logger?.Invoke(_Header + "XML exception: " + Environment.NewLine + Common.SerializeJson(ioe, true));
                            await s3ctx.Response.Send(S3Objects.ErrorCode.MalformedXML).ConfigureAwait(false);

                            return;
                        }

                        await Object.WriteAcl(s3ctx, acp).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectWriteLegalHold:
                    if (Object.WriteLegalHold != null)
                    {
                        try
                        {
                            legalHold = Common.DeserializeXml <LegalHold>(s3ctx.Request.DataAsString);
                        }
                        catch (InvalidOperationException ioe)
                        {
                            ioe.Data.Add("Context", s3ctx);
                            ioe.Data.Add("RequestBody", s3ctx.Request.DataAsString);
                            Logger?.Invoke(_Header + "XML exception: " + Environment.NewLine + Common.SerializeJson(ioe, true));
                            await s3ctx.Response.Send(S3Objects.ErrorCode.MalformedXML).ConfigureAwait(false);

                            return;
                        }

                        await Object.WriteLegalHold(s3ctx, legalHold).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectWriteRetention:
                    if (Object.WriteRetention != null)
                    {
                        try
                        {
                            retention = Common.DeserializeXml <Retention>(s3ctx.Request.DataAsString);
                        }
                        catch (InvalidOperationException ioe)
                        {
                            ioe.Data.Add("Context", s3ctx);
                            ioe.Data.Add("RequestBody", s3ctx.Request.DataAsString);
                            Logger?.Invoke(_Header + "XML exception: " + Environment.NewLine + Common.SerializeJson(ioe, true));
                            await s3ctx.Response.Send(S3Objects.ErrorCode.MalformedXML).ConfigureAwait(false);

                            return;
                        }

                        await Object.WriteRetention(s3ctx, retention).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectWriteTags:
                    if (Object.WriteTagging != null)
                    {
                        try
                        {
                            tagging = Common.DeserializeXml <Tagging>(s3ctx.Request.DataAsString);
                        }
                        catch (InvalidOperationException ioe)
                        {
                            ioe.Data.Add("Context", s3ctx);
                            ioe.Data.Add("RequestBody", s3ctx.Request.DataAsString);
                            Logger?.Invoke(_Header + "XML exception: " + Environment.NewLine + Common.SerializeJson(ioe, true));
                            await s3ctx.Response.Send(S3Objects.ErrorCode.MalformedXML).ConfigureAwait(false);

                            return;
                        }

                        await Object.WriteTagging(s3ctx, tagging).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                    #endregion
                }

                if (DefaultRequestHandler != null)
                {
                    await DefaultRequestHandler(s3ctx).ConfigureAwait(false);

                    return;
                }

                await s3ctx.Response.Send(S3Objects.ErrorCode.InvalidRequest).ConfigureAwait(false);

                return;
            }
            catch (S3Exception s3e)
            {
                if (Logging.Exceptions)
                {
                    Logger?.Invoke(_Header + "S3 exception:" + Environment.NewLine + Common.SerializeJson(s3e, true));
                }

                await s3ctx.Response.Send(s3e.Error).ConfigureAwait(false);

                return;
            }
            catch (Exception e)
            {
                if (Logging.Exceptions)
                {
                    Logger?.Invoke(_Header + "exception:" + Environment.NewLine + Common.SerializeJson(e, true));
                }

                await s3ctx.Response.Send(S3Objects.ErrorCode.InternalError).ConfigureAwait(false);

                return;
            }
            finally
            {
                if (Logging.HttpRequests)
                {
                    Logger?.Invoke(
                        _Header +
                        "[" +
                        ctx.Request.Source.IpAddress + ":" +
                        ctx.Request.Source.Port +
                        "] " +
                        ctx.Request.Method.ToString() + " " +
                        ctx.Request.Url.RawWithoutQuery + " " +
                        s3ctx.Response.StatusCode +
                        " [" + Common.TotalMsFrom(startTime) + "ms]");
                }

                if (PostRequestHandler != null)
                {
                    await PostRequestHandler(s3ctx).ConfigureAwait(false);
                }
            }
        }
예제 #14
0
        public static string BuildWebsiteConfiguration(WebsiteConfiguration websiteConfiguration)
        {
            StringWriter      stringWriter     = new StringWriter();
            XmlWriterSettings xmlWriterSetting = new XmlWriterSettings();

            xmlWriterSetting.Indent = true;

            XmlWriter xmlWriter = XmlWriter.Create(stringWriter, xmlWriterSetting);

            xmlWriter.WriteStartDocument();
            xmlWriter.WriteStartElement("WebsiteConfiguration");

            if (websiteConfiguration.indexDocument != null)
            {
                xmlWriter.WriteStartElement("IndexDocument");
                xmlWriter.WriteElementString("Suffix", websiteConfiguration.indexDocument.suffix);
                xmlWriter.WriteEndElement();
            }

            if (websiteConfiguration.errorDocument != null)
            {
                xmlWriter.WriteStartElement("ErrorDocument");
                xmlWriter.WriteElementString("Key", websiteConfiguration.errorDocument.key);
                xmlWriter.WriteEndElement();
            }

            if (websiteConfiguration.redirectAllRequestTo != null)
            {
                xmlWriter.WriteStartElement("RedirectAllRequestTo");
                xmlWriter.WriteElementString("Protocol", websiteConfiguration.redirectAllRequestTo.protocol);
                xmlWriter.WriteEndElement();
            }

            if (websiteConfiguration.routingRules != null && websiteConfiguration.routingRules.Count > 0)
            {
                xmlWriter.WriteStartElement("RoutingRules");
                foreach (WebsiteConfiguration.RoutingRule routingRule in websiteConfiguration.routingRules)
                {
                    xmlWriter.WriteStartElement("RoutingRule");
                    if (routingRule.contidion != null)
                    {
                        xmlWriter.WriteStartElement("Condition");
                        xmlWriter.WriteElementString("HttpErrorCodeReturnedEquals", routingRule.contidion.httpErrorCodeReturnedEquals.ToString());
                        xmlWriter.WriteElementString("KeyPrefixEquals", routingRule.contidion.keyPrefixEquals);
                        xmlWriter.WriteEndElement();
                    }
                    if (routingRule.redirect != null)
                    {
                        xmlWriter.WriteStartElement("Redirect");
                        xmlWriter.WriteElementString("Protocol", routingRule.redirect.protocol);
                        xmlWriter.WriteElementString("ReplaceKeyPrefixWith", routingRule.redirect.replaceKeyPrefixWith);
                        xmlWriter.WriteElementString("ReplaceKeyWith", routingRule.redirect.replaceKeyWith);
                        xmlWriter.WriteEndElement();
                    }
                    xmlWriter.WriteEndElement();
                }
                xmlWriter.WriteEndElement();
            }
            // end to element
            xmlWriter.WriteEndElement();

            xmlWriter.WriteEndDocument();
            xmlWriter.Flush();
            return(RemoveXMLHeader(stringWriter.ToString()));
        }
예제 #15
0
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
        static async Task BucketWriteWebsite(S3Context ctx, WebsiteConfiguration website)
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
        {
            Console.WriteLine("BucketWriteWebsite: " + ctx.Request.Bucket);
            Console.WriteLine(ctx.Request.DataAsString + Environment.NewLine);
        }
예제 #16
0
 public TestController(ILogger logger, IDataSetsHelper dataSetsHelper, IRoles roles, IAuthentication authentication, IMailer mailer, IOptions <WebsiteConfiguration> config, IFileSourceHelper fileSourceHelper)
     : base(logger, dataSetsHelper, roles, authentication, fileSourceHelper)
 {
     _mailer = mailer;
     _config = config.Value;
 }
예제 #17
0
 public Task <PutBucketWebsiteResponse> PutBucketWebsiteAsync(string bucketName, WebsiteConfiguration websiteConfiguration, CancellationToken cancellationToken = default)
 {
     throw new NotImplementedException();
 }
예제 #18
0
 public ContentPlugin(WebsiteConfiguration config)
     : base(config)
 {
 }
 internal override void ParseResponseBody(System.IO.Stream inputStream, string contentType, long contentLength)
 {
     websiteConfiguration = new WebsiteConfiguration();
     XmlParse.ParseWebsiteConfig(inputStream, websiteConfiguration);
 }
예제 #20
0
 public AdminPlugin(WebsiteConfiguration websiteConfiguration)
 {
     this.websiteConfiguration = websiteConfiguration;
 }
예제 #21
0
 public PutBucketWebsiteRequest(string bucket) : base(bucket)
 {
     this.method = CosRequestMethod.PUT;
     this.queryParameters.Add("website", null);
     websiteConfiguration = new WebsiteConfiguration();
 }
예제 #22
0
 public ContentPluginBase(WebsiteConfiguration configuration)
 {
     this.configuration = configuration;
 }
예제 #23
0
 public ThemeController(WebsiteConfiguration websiteConfiguration)
 {
     this.websiteConfiguration = websiteConfiguration;
 }
예제 #24
0
 public void PutBucketWebsiteAsync(string bucketName, WebsiteConfiguration websiteConfiguration, AmazonServiceCallback <PutBucketWebsiteRequest, PutBucketWebsiteResponse> callback, AsyncOptions options = null)
 {
     throw new System.NotImplementedException();
 }
예제 #25
0
        public void TestBucketWebsite()
        {
            try
            {
                PutBucketWebsiteRequest putRequest = new PutBucketWebsiteRequest(bucket);

                putRequest.SetIndexDocument("index.html");
                putRequest.SetErrorDocument("eroror.html");
                putRequest.SetRedirectAllRequestTo("https");

                var rule = new WebsiteConfiguration.RoutingRule();
                rule.contidion = new WebsiteConfiguration.Contidion();
                // HttpErrorCodeReturnedEquals 与 KeyPrefixEquals 必选其一
                // 只支持配置4XX返回码,例如403或404
                rule.contidion.httpErrorCodeReturnedEquals = 404;
                // rule.contidion.keyPrefixEquals = "test.html";

                rule.redirect          = new WebsiteConfiguration.Redirect();
                rule.redirect.protocol = "https";
                // ReplaceKeyWith 与 ReplaceKeyPrefixWith 必选其一
                // rule.redirect.replaceKeyPrefixWith = "aaa";
                rule.redirect.replaceKeyWith = "bbb";
                putRequest.SetRoutingRules(new List <WebsiteConfiguration.RoutingRule>()
                {
                    rule
                });

                PutBucketWebsiteResult putResult = cosXml.PutBucketWebsite(putRequest);

                Assert.IsTrue(putResult.httpCode == 200);

                QCloudServer.TestWithServerFailTolerance(() =>
                {
                    GetBucketWebsiteRequest getRequest = new GetBucketWebsiteRequest(bucket);

                    GetBucketWebsiteResult getResult = cosXml.GetBucketWebsite(getRequest);
                    // Console.WriteLine(getResult.GetResultInfo());
                    Assert.IsNotEmpty((getResult.GetResultInfo()));

                    WebsiteConfiguration configuration = getResult.websiteConfiguration;

                    Assert.NotNull(configuration);
                    Assert.NotNull(configuration.indexDocument);
                    Assert.NotNull(configuration.indexDocument.suffix);
                    Assert.NotNull(configuration.errorDocument);
                    Assert.NotNull(configuration.redirectAllRequestTo);
                    Assert.NotNull(configuration.redirectAllRequestTo.protocol);
                    Assert.NotZero(configuration.routingRules.Count);
                    Assert.NotNull(configuration.routingRules[0].contidion);
                    Assert.NotNull(configuration.routingRules[0].contidion.httpErrorCodeReturnedEquals);
                    // Assert.NotNull(configuration.routingRules[0].contidion.keyPrefixEquals);
                    Assert.NotNull(configuration.routingRules[0].redirect);
                    Assert.NotNull(configuration.routingRules[0].redirect.protocol);
                    // Assert.NotNull(configuration.routingRules[0].redirect.replaceKeyPrefixWith);
                    Assert.NotNull(configuration.routingRules[0].redirect.replaceKeyWith);

                    DeleteBucketWebsiteRequest deleteRequest = new DeleteBucketWebsiteRequest(bucket);

                    DeleteBucketWebsiteResult deleteResult = cosXml.DeleteBucketWebsite(deleteRequest);

                    Assert.IsTrue(deleteResult.IsSuccessful());
                }
                                                         );
            }
            catch (COSXML.CosException.CosClientException clientEx)
            {
                Console.WriteLine("CosClientException: " + clientEx.Message);
                Assert.Fail();
            }
            catch (COSXML.CosException.CosServerException serverEx)
            {
                Console.WriteLine("CosServerException: " + serverEx.GetInfo());
                Assert.Fail();
            }
        }
        public IRequest Marshall(PutBucketWebsiteRequest putBucketWebsiteRequest)
        {
            //IL_0006: Unknown result type (might be due to invalid IL or missing references)
            //IL_000c: Expected O, but got Unknown
            //IL_0420: Unknown result type (might be due to invalid IL or missing references)
            IRequest val = new DefaultRequest(putBucketWebsiteRequest, "AmazonS3");

            val.set_HttpMethod("PUT");
            val.set_ResourcePath("/" + S3Transforms.ToStringValue(putBucketWebsiteRequest.BucketName));
            val.AddSubResource("website");
            StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture);

            using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings
            {
                Encoding = Encoding.UTF8,
                OmitXmlDeclaration = true
            }))
            {
                WebsiteConfiguration websiteConfiguration = putBucketWebsiteRequest.WebsiteConfiguration;
                if (websiteConfiguration != null)
                {
                    xmlWriter.WriteStartElement("WebsiteConfiguration", "");
                    if (websiteConfiguration != null)
                    {
                        string errorDocument = websiteConfiguration.ErrorDocument;
                        if (errorDocument != null)
                        {
                            xmlWriter.WriteStartElement("ErrorDocument", "");
                            xmlWriter.WriteElementString("Key", "", S3Transforms.ToXmlStringValue(errorDocument));
                            xmlWriter.WriteEndElement();
                        }
                    }
                    if (websiteConfiguration != null)
                    {
                        string indexDocumentSuffix = websiteConfiguration.IndexDocumentSuffix;
                        if (indexDocumentSuffix != null)
                        {
                            xmlWriter.WriteStartElement("IndexDocument", "");
                            xmlWriter.WriteElementString("Suffix", "", S3Transforms.ToXmlStringValue(indexDocumentSuffix));
                            xmlWriter.WriteEndElement();
                        }
                    }
                    if (websiteConfiguration != null)
                    {
                        RoutingRuleRedirect redirectAllRequestsTo = websiteConfiguration.RedirectAllRequestsTo;
                        if (redirectAllRequestsTo != null)
                        {
                            xmlWriter.WriteStartElement("RedirectAllRequestsTo", "");
                            if (redirectAllRequestsTo.IsSetHostName())
                            {
                                xmlWriter.WriteElementString("HostName", "", S3Transforms.ToXmlStringValue(redirectAllRequestsTo.HostName));
                            }
                            if (redirectAllRequestsTo.IsSetHttpRedirectCode())
                            {
                                xmlWriter.WriteElementString("HttpRedirectCode", "", S3Transforms.ToXmlStringValue(redirectAllRequestsTo.HttpRedirectCode));
                            }
                            if (redirectAllRequestsTo.IsSetProtocol())
                            {
                                xmlWriter.WriteElementString("Protocol", "", S3Transforms.ToXmlStringValue(redirectAllRequestsTo.Protocol));
                            }
                            if (redirectAllRequestsTo.IsSetReplaceKeyPrefixWith())
                            {
                                xmlWriter.WriteElementString("ReplaceKeyPrefixWith", "", S3Transforms.ToXmlStringValue(redirectAllRequestsTo.ReplaceKeyPrefixWith));
                            }
                            if (redirectAllRequestsTo.IsSetReplaceKeyWith())
                            {
                                xmlWriter.WriteElementString("ReplaceKeyWith", "", S3Transforms.ToXmlStringValue(redirectAllRequestsTo.ReplaceKeyWith));
                            }
                            xmlWriter.WriteEndElement();
                        }
                    }
                    if (websiteConfiguration != null)
                    {
                        List <RoutingRule> routingRules = websiteConfiguration.RoutingRules;
                        if (routingRules != null && routingRules.Count > 0)
                        {
                            xmlWriter.WriteStartElement("RoutingRules", "");
                            foreach (RoutingRule item in routingRules)
                            {
                                xmlWriter.WriteStartElement("RoutingRule", "");
                                if (item != null)
                                {
                                    RoutingRuleCondition condition = item.Condition;
                                    if (condition != null)
                                    {
                                        xmlWriter.WriteStartElement("Condition", "");
                                        if (condition.IsSetHttpErrorCodeReturnedEquals())
                                        {
                                            xmlWriter.WriteElementString("HttpErrorCodeReturnedEquals", "", S3Transforms.ToXmlStringValue(condition.HttpErrorCodeReturnedEquals));
                                        }
                                        if (condition.IsSetKeyPrefixEquals())
                                        {
                                            xmlWriter.WriteElementString("KeyPrefixEquals", "", S3Transforms.ToXmlStringValue(condition.KeyPrefixEquals));
                                        }
                                        xmlWriter.WriteEndElement();
                                    }
                                }
                                if (item != null)
                                {
                                    RoutingRuleRedirect redirect = item.Redirect;
                                    if (redirect != null)
                                    {
                                        xmlWriter.WriteStartElement("Redirect", "");
                                        if (redirect.IsSetHostName())
                                        {
                                            xmlWriter.WriteElementString("HostName", "", S3Transforms.ToXmlStringValue(redirect.HostName));
                                        }
                                        if (redirect.IsSetHttpRedirectCode())
                                        {
                                            xmlWriter.WriteElementString("HttpRedirectCode", "", S3Transforms.ToXmlStringValue(redirect.HttpRedirectCode));
                                        }
                                        if (redirect.IsSetProtocol())
                                        {
                                            xmlWriter.WriteElementString("Protocol", "", S3Transforms.ToXmlStringValue(redirect.Protocol));
                                        }
                                        if (redirect.IsSetReplaceKeyPrefixWith())
                                        {
                                            xmlWriter.WriteElementString("ReplaceKeyPrefixWith", "", S3Transforms.ToXmlStringValue(redirect.ReplaceKeyPrefixWith));
                                        }
                                        if (redirect.IsSetReplaceKeyWith())
                                        {
                                            xmlWriter.WriteElementString("ReplaceKeyWith", "", S3Transforms.ToXmlStringValue(redirect.ReplaceKeyWith));
                                        }
                                        xmlWriter.WriteEndElement();
                                    }
                                }
                                xmlWriter.WriteEndElement();
                            }
                            xmlWriter.WriteEndElement();
                        }
                    }
                    xmlWriter.WriteEndElement();
                }
            }
            try
            {
                string text = stringWriter.ToString();
                val.set_Content(Encoding.UTF8.GetBytes(text));
                val.get_Headers()["Content-Type"] = "application/xml";
                string value = AmazonS3Util.GenerateChecksumForContent(text, fBase64Encode: true);
                val.get_Headers()["Content-MD5"] = value;
                return(val);
            }
            catch (EncoderFallbackException ex)
            {
                throw new AmazonServiceException("Unable to marshall request to XML", (Exception)ex);
            }
        }