예제 #1
0
		public static Tag AddTag(string tagText, Tagging.ITaggable objectToTag, Usr usrAddingTag)
		{
			try
			{
				Transaction t = new Transaction();
				try
				{
					Tag tag = Tag.GetTag(tagText);
					if (tag.Blocked)
					{
						throw new InvalidTagException();
					}
					TagPhoto tagPhoto = TagPhoto.GetTagPhoto(tag.K, objectToTag.K);
					TagPhotoHistory.TagPhotoHistoryAction action = TagPhotoHistory.TagPhotoHistoryAction.Created;
					if (tagPhoto == null)
					{
						tagPhoto = new TagPhoto()
						{
							TagK = tag.K,
							PhotoK = objectToTag.K,
							Disabled = false
						};
						tagPhoto.Update(t);
						action = TagPhotoHistory.TagPhotoHistoryAction.Created;
					}
					if (tagPhoto.Disabled)
					{
						if (!usrAddingTag.IsJunior)
						{
							throw new Exception("You do not have rights to re-enable that tag");
						}
						tagPhoto.Disabled = false;
						tagPhoto.Update(t);
						action = TagPhotoHistory.TagPhotoHistoryAction.Enabled;
					}
					TagPhotoHistory history = new TagPhotoHistory()
					{
						DateTime = DateTime.Now,
						Action = action,
						UsrK = usrAddingTag.K,
						TagPhotoK = tagPhoto.K
					};
					history.Update(t);
					t.Commit();

					return tag;
				}
				catch (Exception ex)
				{
					t.Rollback();
					throw ex;
				}
			}
			catch (InvalidTagException)
			{
				return null;
			}
		}
예제 #2
0
 internal GetBucketTagsResponse(HttpStatusCode statusCode, string responseContent)
     : base(statusCode, responseContent)
 {
     if (string.IsNullOrEmpty(responseContent) ||
         !HttpStatusCode.OK.Equals(statusCode))
     {
         this.BucketTags = null;
         return;
     }
     // Remove namespace from response content, if present.
     responseContent = utils.RemoveNamespaceInXML(responseContent);
     using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(responseContent)))
     {
         this.BucketTags = (Tagging) new XmlSerializer(typeof(Tagging)).Deserialize(stream);
     }
 }
예제 #3
0
        internal static string SerializeTaggingToXml(Tagging tagging)
        {
            var stringWriter = new StringWriter(CultureInfo.InvariantCulture);

            using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings()
            {
                Encoding = Encoding.UTF8, OmitXmlDeclaration = true
            }))
            {
                xmlWriter.WriteStartElement("Tagging", "");

                SerializeTagSetToXml(xmlWriter, tagging.TagSet);

                xmlWriter.WriteEndElement();
            }

            return(stringWriter.ToString());
        }
예제 #4
0
        // Set Replication configuration for the bucket
        public async static Task Run(MinioClient minio,
                                     string bucketName = "my-bucket-name")
        {
            try
            {
                Console.WriteLine("Running example for API: SetBucketReplication");
                Dictionary <string, string> tags = new Dictionary <string, string>()
                {
                    { "key1", "value1" },
                    { "key2", "value2" },
                    { "key3", "value3" }
                };
                ReplicationRule rule =
                    new ReplicationRule(
                        new DeleteMarkerReplication(DeleteMarkerReplication.StatusEnabled),
                        new ReplicationDestination(
                            null, null, "Bucket-ARN", null, null, null, null),
                        null,
                        new RuleFilter(new AndOperator("PREFIX", Tagging.GetBucketTags(tags)), null, null),
                        new DeleteReplication(DeleteReplication.StatusDisabled),
                        1,
                        "REPLICATION-ID",
                        "PREFIX",
                        null,
                        ReplicationRule.StatusEnabled
                        );
                List <ReplicationRule> rules = new List <ReplicationRule>();
                rules.Add(rule);
                ReplicationConfiguration repl = new ReplicationConfiguration("REPLICATION-ROLE", rules);

                await minio.SetBucketReplicationAsync(
                    new SetBucketReplicationArgs()
                    .WithBucket(bucketName)
                    .WithConfiguration(repl)
                    );

                Console.WriteLine($"Bucket Replication set for bucket {bucketName}.");
                Console.WriteLine();
            }
            catch (Exception e)
            {
                Console.WriteLine($"[Bucket]  Exception: {e}");
            }
        }
예제 #5
0
        public static void Main(string[] args)
        {
            // initialize the dynaTrace ADK
            DynaTraceADKFactory.initialize();

            // get an instance of the Tagging ADK
            tagging = DynaTraceADKFactory.createTagging();

            Char c = '0';

            while (c != 'q')
            {
                Console.WriteLine("Available Options:");
                Console.WriteLine("  1 ... start server");
                Console.WriteLine("  2 ... do remote call (by dynaTrace tags)");
                Console.WriteLine("  3 ... do remote call (by custom tagging)");
                Console.WriteLine("  q ... quit");

                String s = Console.ReadLine();
                if (s.Length < 1)
                {
                    continue;
                }
                c = s[0];

                try {
                    switch (c)
                    {
                    case '1': new Server().run(PORT); break;

                    case '2': new Client().run(HOST, PORT, true); break;

                    case '3': new Client().run(HOST, PORT, false); break;

                    case 'q': break;
                    }
                } catch (Exception e) {
                    Console.WriteLine("exception: " + e.Message);
                }
            }

            // uninitialize the dynaTrace ADK
            DynaTraceADKFactory.uninitialize();
        }
예제 #6
0
        public static void RemoveImages(string[] paths)
        {
            foreach (string path in paths)
            {
                Tagging.UnlinkImageTags(FileData[path]);

                ImageData image     = FileData[path];
                ImageType imageType = image.imageType;

                ImagesOfType[imageType].Remove(path);
                ImagesOfTypeRankData[imageType][image.Rank].Remove(path);

                RankData[image.Rank].Remove(path);
                FileData.Remove(path);

                ActiveImages.Remove(path);
                ActiveImagesOfType[imageType].Remove(path);
            }
        }
예제 #7
0
 public RuleFilter(AndOperator theAndOperator, string prefix, Tagging tag)
 {
     this.TheAndOperator = theAndOperator;
     if (string.IsNullOrWhiteSpace(prefix) || string.IsNullOrEmpty(prefix))
     {
         this.Prefix = null;
     }
     else
     {
         this.Prefix = prefix;
     }
     if (tag != null && tag.TaggingSet.Tag.Count == 0)
     {
         tag = null;
     }
     else
     {
         this.Tag = tag;
     }
 }
예제 #8
0
파일: Client.cs 프로젝트: dmauney/Dynatrace
        public void run(string host, int port, bool use_dt_tag)
        {
            TcpClient client  = new TcpClient(host, port);
            Tagging   tagging = MultiAppDotNet.getTagging();

            long a = random.Next();
            long b = random.Next();

            BigEndianReaderWriter rw = new BigEndianReaderWriter(client.GetStream());

            // Either use dynaTrace tags or "custom tags" (passive tagging) for linking remote calls
            if (use_dt_tag)
            {
                // get the current dynaTrace tag and transmit it to the server
                byte[] tag = tagging.getTag();
                rw.WriteByte((byte)tag.Length);
                rw.WriteBytes(tag);
                // insert a synchronous link node
                tagging.linkClientPurePath(false);
            }
            else
            {
                // when using "custom tagging" we're using the data itself as "custom tag"
                CustomTag customTag = tagging.createCustomTag(MultiAppDotNet.getCustomTagFromData(a, b));
                // write a 0 byte, indicating that *no* tag is being sent
                rw.WriteByte((byte)0);
                // insert a synchronous link node using our specific customTag
                tagging.linkClientPurePath(false, customTag);
            }

            // send "payload"
            rw.WriteInt64(a);
            rw.WriteInt64(b);

            // read response from server
            long r = rw.ReadInt64();

            Console.WriteLine(a + "*" + b + "=" + r);

            client.Close();
        }
예제 #9
0
    // Set Tags to the bucket
    public static async Task Run(MinioClient minio,
                                 string bucketName = "my-bucket-name",
                                 Dictionary <string, string> tags = null)
    {
        try
        {
            Console.WriteLine("Running example for API: SetBucketTags");
            await minio.SetBucketTagsAsync(
                new SetBucketTagsArgs()
                .WithBucket(bucketName)
                .WithTagging(Tagging.GetBucketTags(tags))
                );

            Console.WriteLine($"Bucket Tags set for bucket {bucketName}.");
            Console.WriteLine();
        }
        catch (Exception e)
        {
            Console.WriteLine($"[Bucket]  Exception: {e}");
        }
    }
예제 #10
0
        public async Task Tagadd(string tagname, [Remainder] string tagmessage)
        {
            var tg = new Tagging
            {
                Tagname = tagname,
                Content = tagmessage,
                Creator = Context.User.Id
            };
            var file    = Path.Combine(AppContext.BaseDirectory, $"setup/server/{Context.Guild.Id}.json");
            var jsononb = JsonConvert.DeserializeObject <GuildConfig>(File.ReadAllText(file));

            try
            {
                var d = GuildConfig.Load(Context.Guild.Id).Dict;
                foreach (var tagging in d)
                {
                    if (tagging.Tagname == tagname)
                    {
                        await ReplyAsync(
                            $"**{tagname}** is already a tag in this server, if you want to edit it, please delete it first, then add the new tag");

                        return;
                    }
                }
                d.Add(tg);
                jsononb.Dict = d;
                var output = JsonConvert.SerializeObject(jsononb, Formatting.Indented);
                File.WriteAllText(file, output);
                await ReplyAsync("Tags List Updated");
            }
            catch
            {
                var d = new List <Tagging> {
                    tg
                };
                jsononb.Dict = d;
                var output = JsonConvert.SerializeObject(jsononb, Formatting.Indented);
                File.WriteAllText(file, output);
            }
        }
예제 #11
0
파일: Tags.cs 프로젝트: ZeroCry/Passive-BOT
        public async Task Tagadd(string tagname, [Remainder] string tagmessage)
        {
            var tg = new Tagging
            {
                Tagname = tagname,
                Content = tagmessage,
                Creator = Context.User.Id
            };
            var server = GuildConfig.GetServer(Context.Guild);

            if (server.Dict.Any(x => string.Equals(x.Tagname, tagname, StringComparison.CurrentCultureIgnoreCase)))
            {
                await ReplyAsync(
                    $"**{tagname}** is already a tag in this server, if you want to edit it, please delete it first, then add the new tag");

                return;
            }

            server.Dict.Add(tg);
            GuildConfig.SaveServer(server);
            await ReplyAsync("Tags List Updated");
        }
예제 #12
0
        // Set Tags for the object
        public async static Task Run(MinioClient minio,
                                     string bucketName = "my-bucket-name",
                                     string objectName = "my-object-name",
                                     Dictionary <string, string> tags = null,
                                     string versionId = null)
        {
            try
            {
                Console.WriteLine("Running example for API: SetObjectTags");
                var args = new SetObjectTagsArgs()
                           .WithBucket(bucketName)
                           .WithObject(objectName)
                           .WithVersionId(versionId)
                           .WithTagging(Tagging.GetObjectTags(tags));
                await minio.SetObjectTagsAsync(args);

                Console.WriteLine($"Tags set for object {bucketName}/{objectName}.");
                Console.WriteLine();
            }
            catch (Exception e)
            {
                Console.WriteLine($"[Object]  Exception: {e}");
            }
        }
예제 #13
0
		static NamedPipeNativeApplication() {
            DynaTraceADKFactory.initialize();
			tagging = DynaTraceADKFactory.createTagging();
		}
예제 #14
0
 public SetBucketTagsArgs WithTagKeyValuePairs(Dictionary <string, string> kv)
 {
     this.TagKeyValuePairs = new Dictionary <string, string>(kv);
     this.BucketTags       = Tagging.GetBucketTags(kv);
     return(this);
 }
예제 #15
0
        public void TestBucketTagging()
        {
            try
            {
                // 设置 tag
                PutBucketTaggingRequest request = new PutBucketTaggingRequest(bucket);


                string akey   = "aTagKey";
                string avalue = "aTagValue";
                string bkey   = "bTagKey";
                string bvalue = "bTagValue";

                request.AddTag(akey, avalue);
                request.AddTag(bkey, bvalue);

                PutBucketTaggingResult result = cosXml.PutBucketTagging(request);

                Assert.True(result.IsSuccessful());

                // 获取 tag
                GetBucketTaggingRequest getRequest = new GetBucketTaggingRequest(bucket);

                GetBucketTaggingResult getResult = cosXml.GetBucketTagging(getRequest);

                // Console.WriteLine(getResult.GetResultInfo());
                Assert.IsNotEmpty((result.GetResultInfo()));

                Tagging tagging = getResult.tagging;

                Assert.AreEqual(getResult.httpCode, 200);
                Assert.AreEqual(tagging.tagSet.tags.Count, 2);

                foreach (Tagging.Tag tag in tagging.tagSet.tags)
                {
                    if (tag.key.Equals(akey))
                    {
                        Assert.AreEqual(avalue, tag.value);
                    }
                    else if (tag.key.Equals(bkey))
                    {
                        Assert.AreEqual(bvalue, tag.value);
                    }
                    else
                    {
                        Assert.Fail();
                    }
                }

                // 删除 tag
                DeleteBucketTaggingRequest deleteRequest = new DeleteBucketTaggingRequest(bucket);

                DeleteBucketTaggingResult deleteResult = cosXml.DeleteBucketTagging(deleteRequest);
                Assert.True(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();
            }

            try
            {
                // 验证删除成功
                GetBucketTaggingRequest getRequest = new GetBucketTaggingRequest(bucket);

                GetBucketTaggingResult getResult = cosXml.GetBucketTagging(getRequest);
                Assert.Fail();
            }
            catch (COSXML.CosException.CosClientException clientEx)
            {
                Console.WriteLine("CosClientException: " + clientEx.Message);
                Assert.Fail();
            }
            catch (COSXML.CosException.CosServerException serverEx)
            {
                Assert.AreEqual(serverEx.statusCode, 404);
            }
        }
예제 #16
0
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
        static async Task ObjectWriteTags(S3Context ctx, Tagging tags)
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
        {
            Console.WriteLine("ObjectWriteTags: " + ctx.Request.Bucket + "/" + ctx.Request.Key);
            Console.WriteLine(ctx.Request.DataAsString + Environment.NewLine);
        }
예제 #17
0
        static int Main(string[] args)
        {
            bool             ok = true;
            string           sourceFile = null, destFile = null;
            int              padding            = 8192;
            string           encoderMode        = null;
            string           decoderName        = null;
            string           encoderName        = null;
            string           encoderFormat      = null;
            bool             ignore_chunk_sizes = false;
            AudioEncoderType audioEncoderType   = AudioEncoderType.NoAudio;
            var              decoderOptions     = new Dictionary <string, string>();

            for (int arg = 0; arg < args.Length; arg++)
            {
                if (args[arg].Length == 0)
                {
                    ok = false;
                }
                else if (args[arg] == "--ignore-chunk-sizes")
                {
                    ignore_chunk_sizes = true;
                }
                else if (args[arg] == "--decoder" && ++arg < args.Length)
                {
                    decoderName = args[arg];
                }
                else if (args[arg] == "--decoder-option" && arg + 2 < args.Length)
                {
                    var optionName  = args[++arg];
                    var optionValue = args[++arg];
                    decoderOptions.Add(optionName, optionValue);
                }
                else if (args[arg] == "--encoder" && ++arg < args.Length)
                {
                    encoderName = args[arg];
                }
                else if (args[arg] == "--encoder-format" && ++arg < args.Length)
                {
                    encoderFormat = args[arg];
                }
                else if ((args[arg] == "-p" || args[arg] == "--padding") && ++arg < args.Length)
                {
                    ok = int.TryParse(args[arg], out padding);
                }
                else if ((args[arg] == "-m" || args[arg] == "--mode") && ++arg < args.Length)
                {
                    encoderMode = args[arg];
                }
                else if (args[arg] == "--lossy")
                {
                    audioEncoderType = AudioEncoderType.Lossy;
                }
                else if (args[arg] == "--lossless")
                {
                    audioEncoderType = AudioEncoderType.Lossless;
                }
                else if ((args[arg][0] != '-' || args[arg] == "-") && sourceFile == null)
                {
                    sourceFile = args[arg];
                }
                else if ((args[arg][0] != '-' || args[arg] == "-") && sourceFile != null && destFile == null)
                {
                    destFile = args[arg];
                }
                else
                {
                    ok = false;
                }
                if (!ok)
                {
                    break;
                }
            }

            Console.Error.WriteLine("CUETools.Converter, Copyright (C) 2009-2020 Grigory Chudov.");
            Console.Error.WriteLine("This is free software under the GNU GPLv3+ license; There is NO WARRANTY, to");
            Console.Error.WriteLine("the extent permitted by law. <http://www.gnu.org/licenses/> for details.");
            if (!ok || sourceFile == null || destFile == null)
            {
                Usage();
                return(22);
            }

            if (destFile != "-" && destFile != "nul" && File.Exists(destFile))
            {
                Console.Error.WriteLine("Error: file already exists.");
                return(17);
            }

            DateTime start     = DateTime.Now;
            TimeSpan lastPrint = TimeSpan.FromMilliseconds(0);
            var      config    = new CUEConfigAdvanced();

            config.Init();

#if !DEBUG
            try
#endif
            {
                IAudioSource audioSource = null;
                IAudioDest   audioDest   = null;
                TagLib.UserDefined.AdditionalFileTypes.Config = config;
                TagLib.File sourceInfo = sourceFile == "-" ? null : TagLib.File.Create(new TagLib.File.LocalFileAbstraction(sourceFile));

#if !DEBUG
                try
#endif
                {
                    audioSource = Program.GetAudioSource(config, sourceFile, decoderName, ignore_chunk_sizes, decoderOptions);

                    AudioBuffer buff = new AudioBuffer(audioSource, 0x10000);
                    Console.Error.WriteLine("Filename  : {0}", sourceFile);
                    Console.Error.WriteLine("File Info : {0}kHz; {1} channel; {2} bit; {3}", audioSource.PCM.SampleRate, audioSource.PCM.ChannelCount, audioSource.PCM.BitsPerSample, audioSource.Duration);

                    CUEToolsFormat fmt;
                    if (encoderFormat == null)
                    {
                        if (destFile == "-" || destFile == "nul")
                        {
                            encoderFormat = "wav";
                        }
                        else
                        {
                            string extension = Path.GetExtension(destFile).ToLower();
                            if (!extension.StartsWith("."))
                            {
                                throw new Exception("Unknown encoder format: " + destFile);
                            }
                            encoderFormat = extension.Substring(1);
                        }
                    }
                    if (!config.formats.TryGetValue(encoderFormat, out fmt))
                    {
                        throw new Exception("Unsupported encoder format: " + encoderFormat);
                    }
                    AudioEncoderSettingsViewModel encoder =
                        audioEncoderType == AudioEncoderType.Lossless ? Program.GetEncoder(config, fmt, true, encoderName) :
                        audioEncoderType == AudioEncoderType.Lossy ? Program.GetEncoder(config, fmt, false, encoderName) :
                        Program.GetEncoder(config, fmt, true, encoderName) ?? Program.GetEncoder(config, fmt, false, encoderName);
                    if (encoder == null)
                    {
                        var lst = new List <AudioEncoderSettingsViewModel>(config.encodersViewModel).FindAll(
                            e => e.Extension == fmt.extension && (audioEncoderType == AudioEncoderType.NoAudio || audioEncoderType == (e.Lossless ? AudioEncoderType.Lossless : AudioEncoderType.Lossy))).
                                  ConvertAll(e => e.Name + (e.Lossless ? " (lossless)" : " (lossy)"));
                        throw new Exception("Encoders available for format " + fmt.extension + ": " + (lst.Count == 0 ? "none" : string.Join(", ", lst.ToArray())));
                    }
                    var settings = encoder.Settings.Clone();
                    settings.PCM         = audioSource.PCM;
                    settings.Padding     = padding;
                    settings.EncoderMode = encoderMode ?? settings.EncoderMode;
                    object o = null;
                    try
                    {
                        o = destFile == "-" ? Activator.CreateInstance(settings.EncoderType, settings, "", Console.OpenStandardOutput()) :
                            destFile == "nul" ? Activator.CreateInstance(settings.EncoderType, settings, "", new NullStream()) :
                            Activator.CreateInstance(settings.EncoderType, settings, destFile, null);
                    }
                    catch (System.Reflection.TargetInvocationException ex)
                    {
                        throw ex.InnerException;
                    }
                    if (o == null || !(o is IAudioDest))
                    {
                        throw new Exception("Unsupported audio type: " + destFile + ": " + settings.EncoderType.FullName);
                    }
                    audioDest = o as IAudioDest;
                    audioDest.FinalSampleCount = audioSource.Length;

                    bool keepRunning = true;
                    Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e)
                    {
                        keepRunning = false;
                        if (e.SpecialKey == ConsoleSpecialKey.ControlC)
                        {
                            e.Cancel = true;
                        }
                        else
                        {
                            audioDest.Delete();
                        }
                    };

                    while (audioSource.Read(buff, -1) != 0)
                    {
                        audioDest.Write(buff);
                        TimeSpan elapsed = DateTime.Now - start;
                        if ((elapsed - lastPrint).TotalMilliseconds > 60)
                        {
                            var duration = audioSource.Duration;
                            var position = TimeSpan.FromSeconds((double)audioSource.Position / audioSource.PCM.SampleRate);
                            if (duration == TimeSpan.Zero && sourceInfo != null)
                            {
                                duration = sourceInfo.Properties.Duration;
                            }
                            if (duration < position)
                            {
                                duration = position;
                            }
                            if (duration < TimeSpan.FromSeconds(1))
                            {
                                duration = TimeSpan.FromSeconds(1);
                            }
                            Console.Error.Write("\rProgress  : {0:00}%; {1:0.00}x; {2}/{3}",
                                                100.0 * position.TotalSeconds / duration.TotalSeconds,
                                                position.TotalSeconds / elapsed.TotalSeconds,
                                                elapsed,
                                                TimeSpan.FromSeconds(elapsed.TotalSeconds / position.TotalSeconds * duration.TotalSeconds)
                                                );
                            lastPrint = elapsed;
                        }
                        if (!keepRunning)
                        {
                            throw new Exception("Aborted");
                        }
                    }

                    TimeSpan totalElapsed = DateTime.Now - start;
                    Console.Error.Write("\r                                                                         \r");
                    Console.Error.WriteLine("Results   : {0:0.00}x; {1}",
                                            audioSource.Position / totalElapsed.TotalSeconds / audioSource.PCM.SampleRate,
                                            totalElapsed
                                            );
                }
#if !DEBUG
                catch (Exception ex)
                {
                    if (audioSource != null)
                    {
                        audioSource.Close();
                    }
                    if (audioDest != null)
                    {
                        audioDest.Delete();
                    }
                    throw ex;
                }
#endif
                audioSource.Close();
                audioDest.Close();

                if (sourceFile != "-" && destFile != "-" && destFile != "nul")
                {
                    TagLib.File destInfo = TagLib.File.Create(new TagLib.File.LocalFileAbstraction(destFile));
                    if (Tagging.UpdateTags(destInfo, Tagging.Analyze(sourceInfo), config, false))
                    {
                        sourceInfo.Tag.CopyTo(destInfo.Tag, true);
                        destInfo.Tag.Pictures = sourceInfo.Tag.Pictures;
                        destInfo.Save();
                    }
                }
            }
#if !DEBUG
            catch (Exception ex)
            {
                Console.Error.Write("\r                                                                         \r");
                Console.Error.WriteLine("Error     : {0}", ex.Message);
                return(1);
                //Console.WriteLine("{0}", ex.StackTrace);
            }
#endif
            return(0);
        }
예제 #18
0
 public RuleFilter(AndOperator theAndOperator, string prefix, Tagging tag)
 {
     TheAndOperator = theAndOperator;
     Prefix = prefix;
     Tag = tag;
 }
예제 #19
0
        static async Task PutObjectWithTagsTestAsync()
        {
            try
            {
                // 1. Put an object with tags.
                var putRequest = new PutObjectRequest
                {
                    BucketName = bucketName,
                    Key        = keyName,
                    FilePath   = filePath,
                    TagSet     = new List <Tag> {
                        new Tag {
                            Key = "Keyx1", Value = "Value1"
                        },
                        new Tag {
                            Key = "Keyx2", Value = "Value2"
                        }
                    }
                };

                PutObjectResponse response = await client.PutObjectAsync(putRequest);

                // 2. Retrieve the object's tags.
                GetObjectTaggingRequest getTagsRequest = new GetObjectTaggingRequest
                {
                    BucketName = bucketName,
                    Key        = keyName
                };

                GetObjectTaggingResponse objectTags = await client.GetObjectTaggingAsync(getTagsRequest);

                for (int i = 0; i < objectTags.Tagging.Count; i++)
                {
                    Console.WriteLine("Key: {0}, Value: {1}", objectTags.Tagging[i].Key, objectTags.Tagging[i].Value);
                }


                // 3. Replace the tagset.

                Tagging newTagSet = new Tagging();
                newTagSet.TagSet = new List <Tag> {
                    new Tag {
                        Key = "Key3", Value = "Value3"
                    },
                    new Tag {
                        Key = "Key4", Value = "Value4"
                    }
                };


                PutObjectTaggingRequest putObjTagsRequest = new PutObjectTaggingRequest()
                {
                    BucketName = bucketName,
                    Key        = keyName,
                    Tagging    = newTagSet
                };
                PutObjectTaggingResponse response2 = await client.PutObjectTaggingAsync(putObjTagsRequest);

                // 4. Retrieve the object's tags.
                GetObjectTaggingRequest getTagsRequest2 = new GetObjectTaggingRequest();
                getTagsRequest2.BucketName = bucketName;
                getTagsRequest2.Key        = keyName;
                GetObjectTaggingResponse objectTags2 = await client.GetObjectTaggingAsync(getTagsRequest2);

                for (int i = 0; i < objectTags2.Tagging.Count; i++)
                {
                    Console.WriteLine("Key: {0}, Value: {1}", objectTags2.Tagging[i].Key, objectTags2.Tagging[i].Value);
                }
            }
            catch (AmazonS3Exception e)
            {
                Console.WriteLine(
                    "Error encountered ***. Message:'{0}' when writing an object"
                    , e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine(
                    "Encountered an error. Message:'{0}' when writing an object"
                    , e.Message);
            }
        }
 public SetBucketTagsArgs WithTagging(Tagging tags)
 {
     BucketTags = Tagging.GetObjectTags(tags.GetTags());
     return(this);
 }
 internal override void ParseResponseBody(System.IO.Stream inputStream, string contentType, long contentLength)
 {
     tagging = new Tagging();
     XmlParse.ParseTagging(inputStream, tagging);
 }
예제 #22
0
 public RuleFilter(AndOperator theAndOperator, string prefix, Tagging tag)
 {
     this.TheAndOperator = theAndOperator;
     this.Prefix         = prefix;
     this.Tag            = tag;
 }
예제 #23
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);
                }
            }
        }
예제 #24
0
 public T WithTagging(Tagging tagging)
 {
     ObjectTags = tagging;
     return((T)this);
 }
예제 #25
0
 public AndOperator(string prefix, Tagging tagObj)
 {
     Prefix = prefix;
     Tags   = new List <Tag>(tagObj.TaggingSet.Tag);
 }