OSDN Git Service

using var を使用する
authorKimura Youichi <kim.upsilon@bucyou.net>
Sat, 17 Aug 2019 08:27:55 +0000 (17:27 +0900)
committerKimura Youichi <kim.upsilon@bucyou.net>
Fri, 30 Aug 2019 18:08:58 +0000 (03:08 +0900)
47 files changed:
OpenTween.Tests/Api/BitlyApiTest.cs
OpenTween.Tests/Api/MicrosoftTranslatorApiTest.cs
OpenTween.Tests/Api/TwitterApiTest.cs
OpenTween.Tests/Connection/LazyJsonTest.cs
OpenTween.Tests/Connection/OAuthHandlerTest.cs
OpenTween.Tests/Connection/OAuthUtilityTest.cs
OpenTween.Tests/Connection/TwitterApiConnectionTest.cs
OpenTween.Tests/HashtagManageTest.cs
OpenTween.Tests/MediaSelectorTest.cs
OpenTween/Api/BitlyApi.cs
OpenTween/Api/MicrosoftTranslatorApi.cs
OpenTween/Api/TwitterStreamObservable.cs
OpenTween/ApplicationEvents.cs
OpenTween/AuthDialog.cs
OpenTween/Connection/Imgur.cs
OpenTween/Connection/LazyJson.cs
OpenTween/Connection/Mobypicture.cs
OpenTween/Connection/OAuthUtility.cs
OpenTween/Connection/TwitterApiConnection.cs
OpenTween/Connection/TwitterPhoto.cs
OpenTween/EventViewerDialog.cs
OpenTween/Extensions.cs
OpenTween/FilterDialog.cs
OpenTween/Growl.cs
OpenTween/ImageCache.cs
OpenTween/InputDialog.cs
OpenTween/ListAvailable.cs
OpenTween/ListManage.cs
OpenTween/MediaItem.cs
OpenTween/MemoryImage.cs
OpenTween/MyCommon.cs
OpenTween/Setting/Panel/ActionPanel.cs
OpenTween/Setting/Panel/ShortUrlPanel.cs
OpenTween/Setting/SettingBase.cs
OpenTween/ShortUrl.cs
OpenTween/Thumbnail/MapThumbOSM.cs
OpenTween/Thumbnail/Services/FoursquareCheckin.cs
OpenTween/Thumbnail/Services/ImgAzyobuziNet.cs
OpenTween/Thumbnail/Services/MetaThumbnailService.cs
OpenTween/Thumbnail/Services/Pixiv.cs
OpenTween/Thumbnail/Services/Tinami.cs
OpenTween/Thumbnail/Services/TonTwitterCom.cs
OpenTween/Thumbnail/Services/Tumblr.cs
OpenTween/Thumbnail/ThumbnailInfo.cs
OpenTween/Tween.cs
OpenTween/TweetDetailsView.cs
OpenTween/UserInfoDialog.cs

index 1703e15..afed8d0 100644 (file)
@@ -36,138 +36,130 @@ namespace OpenTween.Api
         [Fact]
         public async Task ShortenAsync_OAuth2Test()
         {
-            using (var mockHandler = new HttpMessageHandlerMock())
-            using (var http = new HttpClient(mockHandler))
-            {
-                var bitly = new BitlyApi(http);
+            using var mockHandler = new HttpMessageHandlerMock();
+            using var http = new HttpClient(mockHandler);
+            var bitly = new BitlyApi(http);
 
-                mockHandler.Enqueue(x =>
-                {
-                    Assert.Equal(HttpMethod.Get, x.Method);
-                    Assert.Equal("https://api-ssl.bitly.com/v3/shorten",
-                        x.RequestUri.GetLeftPart(UriPartial.Path));
+            mockHandler.Enqueue(x =>
+            {
+                Assert.Equal(HttpMethod.Get, x.Method);
+                Assert.Equal("https://api-ssl.bitly.com/v3/shorten",
+                    x.RequestUri.GetLeftPart(UriPartial.Path));
 
-                    var query = HttpUtility.ParseQueryString(x.RequestUri.Query);
+                var query = HttpUtility.ParseQueryString(x.RequestUri.Query);
 
-                    Assert.Equal("http://www.example.com/", query["longUrl"]);
-                    Assert.Equal("bit.ly", query["domain"]);
-                    Assert.Equal("hogehoge", query["access_token"]);
+                Assert.Equal("http://www.example.com/", query["longUrl"]);
+                Assert.Equal("bit.ly", query["domain"]);
+                Assert.Equal("hogehoge", query["access_token"]);
 
-                    return new HttpResponseMessage(HttpStatusCode.OK)
-                    {
-                        Content = new StringContent("http://bit.ly/foo"),
-                    };
-                });
+                return new HttpResponseMessage(HttpStatusCode.OK)
+                {
+                    Content = new StringContent("http://bit.ly/foo"),
+                };
+            });
 
-                bitly.EndUserAccessToken = "hogehoge";
+            bitly.EndUserAccessToken = "hogehoge";
 
-                var result = await bitly.ShortenAsync(new Uri("http://www.example.com/"), "bit.ly")
-                    .ConfigureAwait(false);
-                Assert.Equal("http://bit.ly/foo", result.OriginalString);
+            var result = await bitly.ShortenAsync(new Uri("http://www.example.com/"), "bit.ly")
+                .ConfigureAwait(false);
+            Assert.Equal("http://bit.ly/foo", result.OriginalString);
 
-                Assert.Equal(0, mockHandler.QueueCount);
-            }
+            Assert.Equal(0, mockHandler.QueueCount);
         }
 
         [Fact]
         public async Task ShortenAsync_LegacyApiKeyTest()
         {
-            using (var mockHandler = new HttpMessageHandlerMock())
-            using (var http = new HttpClient(mockHandler))
-            {
-                var bitly = new BitlyApi(http);
+            using var mockHandler = new HttpMessageHandlerMock();
+            using var http = new HttpClient(mockHandler);
+            var bitly = new BitlyApi(http);
 
-                mockHandler.Enqueue(x =>
-                {
-                    Assert.Equal(HttpMethod.Get, x.Method);
-                    Assert.Equal("https://api-ssl.bitly.com/v3/shorten",
-                        x.RequestUri.GetLeftPart(UriPartial.Path));
+            mockHandler.Enqueue(x =>
+            {
+                Assert.Equal(HttpMethod.Get, x.Method);
+                Assert.Equal("https://api-ssl.bitly.com/v3/shorten",
+                    x.RequestUri.GetLeftPart(UriPartial.Path));
 
-                    var query = HttpUtility.ParseQueryString(x.RequestUri.Query);
+                var query = HttpUtility.ParseQueryString(x.RequestUri.Query);
 
-                    Assert.Equal("http://www.example.com/", query["longUrl"]);
-                    Assert.Equal("bit.ly", query["domain"]);
-                    Assert.Equal("username", query["login"]);
-                    Assert.Equal("hogehoge", query["apiKey"]);
+                Assert.Equal("http://www.example.com/", query["longUrl"]);
+                Assert.Equal("bit.ly", query["domain"]);
+                Assert.Equal("username", query["login"]);
+                Assert.Equal("hogehoge", query["apiKey"]);
 
-                    return new HttpResponseMessage(HttpStatusCode.OK)
-                    {
-                        Content = new StringContent("http://bit.ly/foo"),
-                    };
-                });
+                return new HttpResponseMessage(HttpStatusCode.OK)
+                {
+                    Content = new StringContent("http://bit.ly/foo"),
+                };
+            });
 
-                bitly.EndUserLoginName = "username";
-                bitly.EndUserApiKey = "hogehoge";
+            bitly.EndUserLoginName = "username";
+            bitly.EndUserApiKey = "hogehoge";
 
-                var result = await bitly.ShortenAsync(new Uri("http://www.example.com/"), "bit.ly")
-                    .ConfigureAwait(false);
-                Assert.Equal("http://bit.ly/foo", result.OriginalString);
+            var result = await bitly.ShortenAsync(new Uri("http://www.example.com/"), "bit.ly")
+                .ConfigureAwait(false);
+            Assert.Equal("http://bit.ly/foo", result.OriginalString);
 
-                Assert.Equal(0, mockHandler.QueueCount);
-            }
+            Assert.Equal(0, mockHandler.QueueCount);
         }
 
         [Fact]
         public async Task GetAccessTokenAsync_Test()
         {
-            using (var mockHandler = new HttpMessageHandlerMock())
-            using (var http = new HttpClient(mockHandler))
+            using var mockHandler = new HttpMessageHandlerMock();
+            using var http = new HttpClient(mockHandler);
+            var bitly = new BitlyApi(http);
+
+            mockHandler.Enqueue(async x =>
             {
-                var bitly = new BitlyApi(http);
+                Assert.Equal(HttpMethod.Post, x.Method);
+                Assert.Equal("https://api-ssl.bitly.com/oauth/access_token",
+                    x.RequestUri.GetLeftPart(UriPartial.Path));
 
-                mockHandler.Enqueue(async x =>
-                {
-                    Assert.Equal(HttpMethod.Post, x.Method);
-                    Assert.Equal("https://api-ssl.bitly.com/oauth/access_token",
-                        x.RequestUri.GetLeftPart(UriPartial.Path));
+                Assert.Equal("Basic", x.Headers.Authorization.Scheme);
+                Assert.Equal(ApplicationSettings.BitlyClientId + ":" + ApplicationSettings.BitlyClientSecret,
+                    Encoding.UTF8.GetString(Convert.FromBase64String(x.Headers.Authorization.Parameter)));
 
-                    Assert.Equal("Basic", x.Headers.Authorization.Scheme);
-                    Assert.Equal(ApplicationSettings.BitlyClientId + ":" + ApplicationSettings.BitlyClientSecret,
-                        Encoding.UTF8.GetString(Convert.FromBase64String(x.Headers.Authorization.Parameter)));
+                var body = await x.Content.ReadAsStringAsync()
+                    .ConfigureAwait(false);
+                var query = HttpUtility.ParseQueryString(body);
 
-                    var body = await x.Content.ReadAsStringAsync()
-                        .ConfigureAwait(false);
-                    var query = HttpUtility.ParseQueryString(body);
+                Assert.Equal("password", query["grant_type"]);
+                Assert.Equal("hogehoge", query["username"]);
+                Assert.Equal("tetete", query["password"]);
 
-                    Assert.Equal("password", query["grant_type"]);
-                    Assert.Equal("hogehoge", query["username"]);
-                    Assert.Equal("tetete", query["password"]);
+                return new HttpResponseMessage(HttpStatusCode.OK)
+                {
+                    Content = new StringContent("{\"access_token\": \"abcdefg\"}"),
+                };
+            });
 
-                    return new HttpResponseMessage(HttpStatusCode.OK)
-                    {
-                        Content = new StringContent("{\"access_token\": \"abcdefg\"}"),
-                    };
-                });
+            var result = await bitly.GetAccessTokenAsync("hogehoge", "tetete")
+                .ConfigureAwait(false);
+            Assert.Equal("abcdefg", result);
 
-                var result = await bitly.GetAccessTokenAsync("hogehoge", "tetete")
-                    .ConfigureAwait(false);
-                Assert.Equal("abcdefg", result);
-
-                Assert.Equal(0, mockHandler.QueueCount);
-            }
+            Assert.Equal(0, mockHandler.QueueCount);
         }
 
         [Fact]
         public async Task GetAccessTokenAsync_ErrorResponseTest()
         {
-            using (var mockHandler = new HttpMessageHandlerMock())
-            using (var http = new HttpClient(mockHandler))
-            {
-                var bitly = new BitlyApi(http);
+            using var mockHandler = new HttpMessageHandlerMock();
+            using var http = new HttpClient(mockHandler);
+            var bitly = new BitlyApi(http);
 
-                mockHandler.Enqueue(x =>
+            mockHandler.Enqueue(x =>
+            {
+                return new HttpResponseMessage(HttpStatusCode.OK)
                 {
-                    return new HttpResponseMessage(HttpStatusCode.OK)
-                    {
-                        Content = new StringContent("{\"status_code\": \"500\", \"status_txt\": \"MISSING_ARG_USERNAME\"}"),
-                    };
-                });
+                    Content = new StringContent("{\"status_code\": \"500\", \"status_txt\": \"MISSING_ARG_USERNAME\"}"),
+                };
+            });
 
-                await Assert.ThrowsAsync<WebApiException>(() => bitly.GetAccessTokenAsync("hogehoge", "tetete"))
-                    .ConfigureAwait(false);
+            await Assert.ThrowsAsync<WebApiException>(() => bitly.GetAccessTokenAsync("hogehoge", "tetete"))
+                .ConfigureAwait(false);
 
-                Assert.Equal(0, mockHandler.QueueCount);
-            }
+            Assert.Equal(0, mockHandler.QueueCount);
         }
     }
 }
index d02e97d..84e2696 100644 (file)
@@ -39,41 +39,41 @@ namespace OpenTween.Api
         [Fact]
         public async Task TranslateAsync_Test()
         {
-            using (var mockHandler = new HttpMessageHandlerMock())
-            using (var http = new HttpClient(mockHandler))
-            {
-                var mock = new Mock<MicrosoftTranslatorApi>(http);
-                mock.Setup(x => x.GetAccessTokenAsync())
-                    .ReturnsAsync(("1234abcd", TimeSpan.FromSeconds(1000)));
+            using var mockHandler = new HttpMessageHandlerMock();
+            using var http = new HttpClient(mockHandler);
 
-                var translateApi = mock.Object;
+            var mock = new Mock<MicrosoftTranslatorApi>(http);
+            mock.Setup(x => x.GetAccessTokenAsync())
+                .ReturnsAsync(("1234abcd", TimeSpan.FromSeconds(1000)));
 
-                mockHandler.Enqueue(async x =>
-                {
-                    Assert.Equal(HttpMethod.Post, x.Method);
-                    Assert.Equal(MicrosoftTranslatorApi.TranslateEndpoint.AbsoluteUri,
-                        x.RequestUri.GetLeftPart(UriPartial.Path));
+            var translateApi = mock.Object;
 
-                    var query = HttpUtility.ParseQueryString(x.RequestUri.Query);
+            mockHandler.Enqueue(async x =>
+            {
+                Assert.Equal(HttpMethod.Post, x.Method);
+                Assert.Equal(MicrosoftTranslatorApi.TranslateEndpoint.AbsoluteUri,
+                    x.RequestUri.GetLeftPart(UriPartial.Path));
 
-                    Assert.Equal("3.0", query["api-version"]);
-                    Assert.Equal("ja", query["to"]);
-                    Assert.Equal("en", query["from"]);
+                var query = HttpUtility.ParseQueryString(x.RequestUri.Query);
 
-                    var requestBody = await x.Content.ReadAsByteArrayAsync()
-                        .ConfigureAwait(false);
+                Assert.Equal("3.0", query["api-version"]);
+                Assert.Equal("ja", query["to"]);
+                Assert.Equal("en", query["from"]);
 
-                    using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(requestBody, XmlDictionaryReaderQuotas.Max))
-                    {
-                        var xElm = XElement.Load(jsonReader);
+                var requestBody = await x.Content.ReadAsByteArrayAsync()
+                    .ConfigureAwait(false);
 
-                        var textElm = xElm.XPathSelectElement("/item/Text");
-                        Assert.Equal("hogehoge", textElm.Value);
-                    }
+                using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(requestBody, XmlDictionaryReaderQuotas.Max))
+                {
+                    var xElm = XElement.Load(jsonReader);
 
-                    return new HttpResponseMessage(HttpStatusCode.OK)
-                    {
-                        Content = new StringContent(@"[
+                    var textElm = xElm.XPathSelectElement("/item/Text");
+                    Assert.Equal("hogehoge", textElm.Value);
+                }
+
+                return new HttpResponseMessage(HttpStatusCode.OK)
+                {
+                    Content = new StringContent(@"[
     {
         ""translations"": [
             {
@@ -83,16 +83,15 @@ namespace OpenTween.Api
         ]
     }
 ]"),
-                    };
-                });
+                };
+            });
 
-                var result = await translateApi.TranslateAsync("hogehoge", langTo: "ja", langFrom: "en")
-                    .ConfigureAwait(false);
-                Assert.Equal("ほげほげ", result);
+            var result = await translateApi.TranslateAsync("hogehoge", langTo: "ja", langFrom: "en")
+                .ConfigureAwait(false);
+            Assert.Equal("ほげほげ", result);
 
-                mock.Verify(x => x.GetAccessTokenAsync(), Times.Once());
-                Assert.Equal(0, mockHandler.QueueCount);
-            }
+            mock.Verify(x => x.GetAccessTokenAsync(), Times.Once());
+            Assert.Equal(0, mockHandler.QueueCount);
         }
 
         [Fact]
@@ -154,33 +153,31 @@ namespace OpenTween.Api
         [Fact]
         public async Task GetAccessTokenAsync_Test()
         {
-            using (var mockHandler = new HttpMessageHandlerMock())
-            using (var http = new HttpClient(mockHandler))
-            {
-                var translateApi = new MicrosoftTranslatorApi(http);
+            using var mockHandler = new HttpMessageHandlerMock();
+            using var http = new HttpClient(mockHandler);
+            var translateApi = new MicrosoftTranslatorApi(http);
 
-                mockHandler.Enqueue(x =>
-                {
-                    Assert.Equal(HttpMethod.Post, x.Method);
-                    Assert.Equal(MicrosoftTranslatorApi.IssueTokenEndpoint, x.RequestUri);
+            mockHandler.Enqueue(x =>
+            {
+                Assert.Equal(HttpMethod.Post, x.Method);
+                Assert.Equal(MicrosoftTranslatorApi.IssueTokenEndpoint, x.RequestUri);
 
-                    var keyHeader = x.Headers.First(y => y.Key == "Ocp-Apim-Subscription-Key");
-                    Assert.Equal(ApplicationSettings.TranslatorSubscriptionKey, keyHeader.Value.Single());
+                var keyHeader = x.Headers.First(y => y.Key == "Ocp-Apim-Subscription-Key");
+                Assert.Equal(ApplicationSettings.TranslatorSubscriptionKey, keyHeader.Value.Single());
 
-                    return new HttpResponseMessage(HttpStatusCode.OK)
-                    {
-                        Content = new StringContent(@"ACCESS_TOKEN"),
-                    };
-                });
+                return new HttpResponseMessage(HttpStatusCode.OK)
+                {
+                    Content = new StringContent(@"ACCESS_TOKEN"),
+                };
+            });
 
-                var result = await translateApi.GetAccessTokenAsync()
-                    .ConfigureAwait(false);
+            var result = await translateApi.GetAccessTokenAsync()
+                .ConfigureAwait(false);
 
-                var expectedToken = (@"ACCESS_TOKEN", TimeSpan.FromMinutes(10));
-                Assert.Equal(expectedToken, result);
+            var expectedToken = (@"ACCESS_TOKEN", TimeSpan.FromMinutes(10));
+            Assert.Equal(expectedToken, result);
 
-                Assert.Equal(0, mockHandler.QueueCount);
-            }
+            Assert.Equal(0, mockHandler.QueueCount);
         }
     }
 }
index 1e68b62..6bd0d1e 100644 (file)
@@ -51,108 +51,100 @@ namespace OpenTween.Api
         [Fact]
         public void Initialize_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                Assert.Null(twitterApi.apiConnection);
+            using var twitterApi = new TwitterApi();
+            Assert.Null(twitterApi.apiConnection);
 
-                twitterApi.Initialize("*** AccessToken ***", "*** AccessSecret ***", userId: 100L, screenName: "hogehoge");
+            twitterApi.Initialize("*** AccessToken ***", "*** AccessSecret ***", userId: 100L, screenName: "hogehoge");
 
-                Assert.IsType<TwitterApiConnection>(twitterApi.apiConnection);
+            Assert.IsType<TwitterApiConnection>(twitterApi.apiConnection);
 
-                var apiConnection = (TwitterApiConnection)twitterApi.apiConnection;
-                Assert.Equal("*** AccessToken ***", apiConnection.AccessToken);
-                Assert.Equal("*** AccessSecret ***", apiConnection.AccessSecret);
+            var apiConnection = (TwitterApiConnection)twitterApi.apiConnection!;
+            Assert.Equal("*** AccessToken ***", apiConnection.AccessToken);
+            Assert.Equal("*** AccessSecret ***", apiConnection.AccessSecret);
 
-                Assert.Equal(100L, twitterApi.CurrentUserId);
-                Assert.Equal("hogehoge", twitterApi.CurrentScreenName);
+            Assert.Equal(100L, twitterApi.CurrentUserId);
+            Assert.Equal("hogehoge", twitterApi.CurrentScreenName);
 
-                // 複数回 Initialize を実行した場合は新たに TwitterApiConnection が生成される
-                twitterApi.Initialize("*** AccessToken2 ***", "*** AccessSecret2 ***", userId: 200L, screenName: "foobar");
+            // 複数回 Initialize を実行した場合は新たに TwitterApiConnection が生成される
+            twitterApi.Initialize("*** AccessToken2 ***", "*** AccessSecret2 ***", userId: 200L, screenName: "foobar");
 
-                var oldApiConnection = apiConnection;
-                Assert.True(oldApiConnection.IsDisposed);
+            var oldApiConnection = apiConnection;
+            Assert.True(oldApiConnection.IsDisposed);
 
-                Assert.IsType<TwitterApiConnection>(twitterApi.apiConnection);
+            Assert.IsType<TwitterApiConnection>(twitterApi.apiConnection);
 
-                apiConnection = (TwitterApiConnection)twitterApi.apiConnection;
-                Assert.Equal("*** AccessToken2 ***", apiConnection.AccessToken);
-                Assert.Equal("*** AccessSecret2 ***", apiConnection.AccessSecret);
+            apiConnection = (TwitterApiConnection)twitterApi.apiConnection!;
+            Assert.Equal("*** AccessToken2 ***", apiConnection.AccessToken);
+            Assert.Equal("*** AccessSecret2 ***", apiConnection.AccessSecret);
 
-                Assert.Equal(200L, twitterApi.CurrentUserId);
-                Assert.Equal("foobar", twitterApi.CurrentScreenName);
-            }
+            Assert.Equal(200L, twitterApi.CurrentUserId);
+            Assert.Equal("foobar", twitterApi.CurrentScreenName);
         }
 
         [Fact]
         public async Task StatusesHomeTimeline_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.GetAsync<TwitterStatus[]>(
-                        new Uri("statuses/home_timeline.json", UriKind.Relative),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.GetAsync<TwitterStatus[]>(
+                    new Uri("statuses/home_timeline.json", UriKind.Relative),
+                    new Dictionary<string, string> {
                             { "include_entities", "true" },
                             { "include_ext_alt_text", "true" },
                             { "tweet_mode", "extended" },
                             { "count", "200" },
                             { "max_id", "900" },
                             { "since_id", "100" },
-                        },
-                        "/statuses/home_timeline")
-                )
-                .ReturnsAsync(Array.Empty<TwitterStatus>());
+                    },
+                    "/statuses/home_timeline")
+            )
+            .ReturnsAsync(Array.Empty<TwitterStatus>());
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.StatusesHomeTimeline(200, maxId: 900L, sinceId: 100L)
-                    .ConfigureAwait(false);
+            await twitterApi.StatusesHomeTimeline(200, maxId: 900L, sinceId: 100L)
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task StatusesMentionsTimeline_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.GetAsync<TwitterStatus[]>(
-                        new Uri("statuses/mentions_timeline.json", UriKind.Relative),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.GetAsync<TwitterStatus[]>(
+                    new Uri("statuses/mentions_timeline.json", UriKind.Relative),
+                    new Dictionary<string, string> {
                             { "include_entities", "true" },
                             { "include_ext_alt_text", "true" },
                             { "tweet_mode", "extended" },
                             { "count", "200" },
                             { "max_id", "900" },
                             { "since_id", "100" },
-                        },
-                        "/statuses/mentions_timeline")
-                )
-                .ReturnsAsync(Array.Empty<TwitterStatus>());
+                    },
+                    "/statuses/mentions_timeline")
+            )
+            .ReturnsAsync(Array.Empty<TwitterStatus>());
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.StatusesMentionsTimeline(200, maxId: 900L, sinceId: 100L)
-                    .ConfigureAwait(false);
+            await twitterApi.StatusesMentionsTimeline(200, maxId: 900L, sinceId: 100L)
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task StatusesUserTimeline_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.GetAsync<TwitterStatus[]>(
-                        new Uri("statuses/user_timeline.json", UriKind.Relative),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.GetAsync<TwitterStatus[]>(
+                    new Uri("statuses/user_timeline.json", UriKind.Relative),
+                    new Dictionary<string, string> {
                             { "screen_name", "twitterapi" },
                             { "include_rts", "true" },
                             { "include_entities", "true" },
@@ -161,58 +153,54 @@ namespace OpenTween.Api
                             { "count", "200" },
                             { "max_id", "900" },
                             { "since_id", "100" },
-                        },
-                        "/statuses/user_timeline")
-                )
-                .ReturnsAsync(Array.Empty<TwitterStatus>());
+                    },
+                    "/statuses/user_timeline")
+            )
+            .ReturnsAsync(Array.Empty<TwitterStatus>());
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.StatusesUserTimeline("twitterapi", count: 200, maxId: 900L, sinceId: 100L)
-                    .ConfigureAwait(false);
+            await twitterApi.StatusesUserTimeline("twitterapi", count: 200, maxId: 900L, sinceId: 100L)
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task StatusesShow_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.GetAsync<TwitterStatus>(
-                        new Uri("statuses/show.json", UriKind.Relative),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.GetAsync<TwitterStatus>(
+                    new Uri("statuses/show.json", UriKind.Relative),
+                    new Dictionary<string, string> {
                             { "id", "100" },
                             { "include_entities", "true" },
                             { "include_ext_alt_text", "true" },
                             { "tweet_mode", "extended" },
-                        },
-                        "/statuses/show/:id")
-                )
-                .ReturnsAsync(new TwitterStatus { Id = 100L });
+                    },
+                    "/statuses/show/:id")
+            )
+            .ReturnsAsync(new TwitterStatus { Id = 100L });
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.StatusesShow(statusId: 100L)
-                    .ConfigureAwait(false);
+            await twitterApi.StatusesShow(statusId: 100L)
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task StatusesUpdate_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.PostLazyAsync<TwitterStatus>(
-                        new Uri("statuses/update.json", UriKind.Relative),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.PostLazyAsync<TwitterStatus>(
+                    new Uri("statuses/update.json", UriKind.Relative),
+                    new Dictionary<string, string> {
                             { "status", "hogehoge" },
                             { "include_entities", "true" },
                             { "include_ext_alt_text", "true" },
@@ -222,112 +210,104 @@ namespace OpenTween.Api
                             { "auto_populate_reply_metadata", "true" },
                             { "exclude_reply_user_ids", "100,200" },
                             { "attachment_url", "https://twitter.com/twitterapi/status/22634515958" },
-                        })
-                )
-                .ReturnsAsync(LazyJson.Create(new TwitterStatus()));
+                    })
+            )
+            .ReturnsAsync(LazyJson.Create(new TwitterStatus()));
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.StatusesUpdate("hogehoge", replyToId: 100L, mediaIds: new[] { 10L, 20L },
-                        autoPopulateReplyMetadata: true, excludeReplyUserIds: new[] { 100L, 200L },
-                        attachmentUrl: "https://twitter.com/twitterapi/status/22634515958")
-                    .IgnoreResponse()
-                    .ConfigureAwait(false);
+            await twitterApi.StatusesUpdate("hogehoge", replyToId: 100L, mediaIds: new[] { 10L, 20L },
+                    autoPopulateReplyMetadata: true, excludeReplyUserIds: new[] { 100L, 200L },
+                    attachmentUrl: "https://twitter.com/twitterapi/status/22634515958")
+                .IgnoreResponse()
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task StatusesUpdate_ExcludeReplyUserIdsEmptyTest()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.PostLazyAsync<TwitterStatus>(
-                        new Uri("statuses/update.json", UriKind.Relative),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.PostLazyAsync<TwitterStatus>(
+                    new Uri("statuses/update.json", UriKind.Relative),
+                    new Dictionary<string, string> {
                             { "status", "hogehoge" },
                             { "include_entities", "true" },
                             { "include_ext_alt_text", "true" },
                             { "tweet_mode", "extended" },
-                            // exclude_reply_user_ids は空の場合には送信されない
-                        })
-                )
-                .ReturnsAsync(LazyJson.Create(new TwitterStatus()));
+                        // exclude_reply_user_ids は空の場合には送信されない
+                    })
+            )
+            .ReturnsAsync(LazyJson.Create(new TwitterStatus()));
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.StatusesUpdate("hogehoge", replyToId: null, mediaIds: null, excludeReplyUserIds: Array.Empty<long>())
-                    .IgnoreResponse()
-                    .ConfigureAwait(false);
+            await twitterApi.StatusesUpdate("hogehoge", replyToId: null, mediaIds: null, excludeReplyUserIds: Array.Empty<long>())
+                .IgnoreResponse()
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task StatusesDestroy_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.PostLazyAsync<TwitterStatus>(
-                        new Uri("statuses/destroy.json", UriKind.Relative),
-                        new Dictionary<string, string> { { "id", "100" } })
-                )
-                .ReturnsAsync(LazyJson.Create(new TwitterStatus { Id = 100L }));
-
-                twitterApi.apiConnection = mock.Object;
-
-                await twitterApi.StatusesDestroy(statusId: 100L)
-                    .IgnoreResponse()
-                    .ConfigureAwait(false);
-
-                mock.VerifyAll();
-            }
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.PostLazyAsync<TwitterStatus>(
+                    new Uri("statuses/destroy.json", UriKind.Relative),
+                    new Dictionary<string, string> { { "id", "100" } })
+            )
+            .ReturnsAsync(LazyJson.Create(new TwitterStatus { Id = 100L }));
+
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
+
+            await twitterApi.StatusesDestroy(statusId: 100L)
+                .IgnoreResponse()
+                .ConfigureAwait(false);
+
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task StatusesRetweet_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.PostLazyAsync<TwitterStatus>(
-                        new Uri("statuses/retweet.json", UriKind.Relative),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.PostLazyAsync<TwitterStatus>(
+                    new Uri("statuses/retweet.json", UriKind.Relative),
+                    new Dictionary<string, string> {
                             { "id", "100" },
                             { "include_entities", "true" },
                             { "include_ext_alt_text", "true" },
                             { "tweet_mode", "extended" },
-                        })
-                )
-                .ReturnsAsync(LazyJson.Create(new TwitterStatus()));
+                    })
+            )
+            .ReturnsAsync(LazyJson.Create(new TwitterStatus()));
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.StatusesRetweet(100L)
-                    .IgnoreResponse()
-                    .ConfigureAwait(false);
+            await twitterApi.StatusesRetweet(100L)
+                .IgnoreResponse()
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task SearchTweets_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.GetAsync<TwitterSearchResult>(
-                        new Uri("search/tweets.json", UriKind.Relative),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.GetAsync<TwitterSearchResult>(
+                    new Uri("search/tweets.json", UriKind.Relative),
+                    new Dictionary<string, string> {
                             { "q", "from:twitterapi" },
                             { "result_type", "recent" },
                             { "include_entities", "true" },
@@ -337,192 +317,178 @@ namespace OpenTween.Api
                             { "count", "200" },
                             { "max_id", "900" },
                             { "since_id", "100" },
-                        },
-                        "/search/tweets")
-                )
-                .ReturnsAsync(new TwitterSearchResult());
+                    },
+                    "/search/tweets")
+            )
+            .ReturnsAsync(new TwitterSearchResult());
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.SearchTweets("from:twitterapi", "en", count: 200, maxId: 900L, sinceId: 100L)
-                    .ConfigureAwait(false);
+            await twitterApi.SearchTweets("from:twitterapi", "en", count: 200, maxId: 900L, sinceId: 100L)
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task ListsOwnerships_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.GetAsync<TwitterLists>(
-                        new Uri("lists/ownerships.json", UriKind.Relative),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.GetAsync<TwitterLists>(
+                    new Uri("lists/ownerships.json", UriKind.Relative),
+                    new Dictionary<string, string> {
                             { "screen_name", "twitterapi" },
                             { "cursor", "-1" },
                             { "count", "100" },
-                        },
-                        "/lists/ownerships")
-                )
-                .ReturnsAsync(new TwitterLists());
+                    },
+                    "/lists/ownerships")
+            )
+            .ReturnsAsync(new TwitterLists());
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.ListsOwnerships("twitterapi", cursor: -1L, count: 100)
-                    .ConfigureAwait(false);
+            await twitterApi.ListsOwnerships("twitterapi", cursor: -1L, count: 100)
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task ListsSubscriptions_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.GetAsync<TwitterLists>(
-                        new Uri("lists/subscriptions.json", UriKind.Relative),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.GetAsync<TwitterLists>(
+                    new Uri("lists/subscriptions.json", UriKind.Relative),
+                    new Dictionary<string, string> {
                             { "screen_name", "twitterapi" },
                             { "cursor", "-1" },
                             { "count", "100" },
-                        },
-                        "/lists/subscriptions")
-                )
-                .ReturnsAsync(new TwitterLists());
+                    },
+                    "/lists/subscriptions")
+            )
+            .ReturnsAsync(new TwitterLists());
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.ListsSubscriptions("twitterapi", cursor: -1L, count: 100)
-                    .ConfigureAwait(false);
+            await twitterApi.ListsSubscriptions("twitterapi", cursor: -1L, count: 100)
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task ListsMemberships_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.GetAsync<TwitterLists>(
-                        new Uri("lists/memberships.json", UriKind.Relative),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.GetAsync<TwitterLists>(
+                    new Uri("lists/memberships.json", UriKind.Relative),
+                    new Dictionary<string, string> {
                             { "screen_name", "twitterapi" },
                             { "cursor", "-1" },
                             { "count", "100" },
                             { "filter_to_owned_lists", "true" },
-                        },
-                        "/lists/memberships")
-                )
-                .ReturnsAsync(new TwitterLists());
+                    },
+                    "/lists/memberships")
+            )
+            .ReturnsAsync(new TwitterLists());
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.ListsMemberships("twitterapi", cursor: -1L, count: 100, filterToOwnedLists: true)
-                    .ConfigureAwait(false);
+            await twitterApi.ListsMemberships("twitterapi", cursor: -1L, count: 100, filterToOwnedLists: true)
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task ListsCreate_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.PostLazyAsync<TwitterList>(
-                        new Uri("lists/create.json", UriKind.Relative),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.PostLazyAsync<TwitterList>(
+                    new Uri("lists/create.json", UriKind.Relative),
+                    new Dictionary<string, string> {
                             { "name", "hogehoge" },
                             { "description", "aaaa" },
                             { "mode", "private" },
-                        })
-                )
-                .ReturnsAsync(LazyJson.Create(new TwitterList()));
+                    })
+            )
+            .ReturnsAsync(LazyJson.Create(new TwitterList()));
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.ListsCreate("hogehoge", description: "aaaa", @private: true)
-                    .IgnoreResponse()
-                    .ConfigureAwait(false);
+            await twitterApi.ListsCreate("hogehoge", description: "aaaa", @private: true)
+                .IgnoreResponse()
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task ListsUpdate_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.PostLazyAsync<TwitterList>(
-                        new Uri("lists/update.json", UriKind.Relative),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.PostLazyAsync<TwitterList>(
+                    new Uri("lists/update.json", UriKind.Relative),
+                    new Dictionary<string, string> {
                             { "list_id", "12345" },
                             { "name", "hogehoge" },
                             { "description", "aaaa" },
                             { "mode", "private" },
-                        })
-                )
-                .ReturnsAsync(LazyJson.Create(new TwitterList()));
+                    })
+            )
+            .ReturnsAsync(LazyJson.Create(new TwitterList()));
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.ListsUpdate(12345L, name: "hogehoge", description: "aaaa", @private: true)
-                    .IgnoreResponse()
-                    .ConfigureAwait(false);
+            await twitterApi.ListsUpdate(12345L, name: "hogehoge", description: "aaaa", @private: true)
+                .IgnoreResponse()
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task ListsDestroy_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.PostLazyAsync<TwitterList>(
-                        new Uri("lists/destroy.json", UriKind.Relative),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.PostLazyAsync<TwitterList>(
+                    new Uri("lists/destroy.json", UriKind.Relative),
+                    new Dictionary<string, string> {
                             { "list_id", "12345" },
-                        })
-                )
-                .ReturnsAsync(LazyJson.Create(new TwitterList()));
+                    })
+            )
+            .ReturnsAsync(LazyJson.Create(new TwitterList()));
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.ListsDestroy(12345L)
-                    .IgnoreResponse()
-                    .ConfigureAwait(false);
+            await twitterApi.ListsDestroy(12345L)
+                .IgnoreResponse()
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task ListsStatuses_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.GetAsync<TwitterStatus[]>(
-                        new Uri("lists/statuses.json", UriKind.Relative),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.GetAsync<TwitterStatus[]>(
+                    new Uri("lists/statuses.json", UriKind.Relative),
+                    new Dictionary<string, string> {
                             { "list_id", "12345" },
                             { "include_entities", "true" },
                             { "include_ext_alt_text", "true" },
@@ -531,172 +497,160 @@ namespace OpenTween.Api
                             { "max_id", "900" },
                             { "since_id", "100" },
                             { "include_rts", "true" },
-                        },
-                        "/lists/statuses")
-                )
-                .ReturnsAsync(Array.Empty<TwitterStatus>());
+                    },
+                    "/lists/statuses")
+            )
+            .ReturnsAsync(Array.Empty<TwitterStatus>());
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.ListsStatuses(12345L, count: 200, maxId: 900L, sinceId: 100L, includeRTs: true)
-                    .ConfigureAwait(false);
+            await twitterApi.ListsStatuses(12345L, count: 200, maxId: 900L, sinceId: 100L, includeRTs: true)
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task ListsMembers_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.GetAsync<TwitterUsers>(
-                        new Uri("lists/members.json", UriKind.Relative),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.GetAsync<TwitterUsers>(
+                    new Uri("lists/members.json", UriKind.Relative),
+                    new Dictionary<string, string> {
                             { "list_id", "12345" },
                             { "include_entities", "true" },
                             { "include_ext_alt_text", "true" },
                             { "tweet_mode", "extended" },
                             { "cursor", "-1" },
-                        },
-                        "/lists/members")
-                )
-                .ReturnsAsync(new TwitterUsers());
+                    },
+                    "/lists/members")
+            )
+            .ReturnsAsync(new TwitterUsers());
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.ListsMembers(12345L, cursor: -1)
-                    .ConfigureAwait(false);
+            await twitterApi.ListsMembers(12345L, cursor: -1)
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task ListsMembersShow_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.GetAsync<TwitterUser>(
-                        new Uri("lists/members/show.json", UriKind.Relative),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.GetAsync<TwitterUser>(
+                    new Uri("lists/members/show.json", UriKind.Relative),
+                    new Dictionary<string, string> {
                             { "list_id", "12345" },
                             { "screen_name", "twitterapi" },
                             { "include_entities", "true" },
                             { "include_ext_alt_text", "true" },
                             { "tweet_mode", "extended" },
-                        },
-                        "/lists/members/show")
-                )
-                .ReturnsAsync(new TwitterUser());
+                    },
+                    "/lists/members/show")
+            )
+            .ReturnsAsync(new TwitterUser());
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.ListsMembersShow(12345L, "twitterapi")
-                    .ConfigureAwait(false);
+            await twitterApi.ListsMembersShow(12345L, "twitterapi")
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task ListsMembersCreate_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.PostLazyAsync<TwitterUser>(
-                        new Uri("lists/members/create.json", UriKind.Relative),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.PostLazyAsync<TwitterUser>(
+                    new Uri("lists/members/create.json", UriKind.Relative),
+                    new Dictionary<string, string> {
                             { "list_id", "12345" },
                             { "screen_name", "twitterapi" },
                             { "include_entities", "true" },
                             { "include_ext_alt_text", "true" },
                             { "tweet_mode", "extended" },
-                        })
-                )
-                .ReturnsAsync(LazyJson.Create(new TwitterUser()));
+                    })
+            )
+            .ReturnsAsync(LazyJson.Create(new TwitterUser()));
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.ListsMembersCreate(12345L, "twitterapi")
-                    .IgnoreResponse()
-                    .ConfigureAwait(false);
+            await twitterApi.ListsMembersCreate(12345L, "twitterapi")
+                .IgnoreResponse()
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task ListsMembersDestroy_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.PostLazyAsync<TwitterUser>(
-                        new Uri("lists/members/destroy.json", UriKind.Relative),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.PostLazyAsync<TwitterUser>(
+                    new Uri("lists/members/destroy.json", UriKind.Relative),
+                    new Dictionary<string, string> {
                             { "list_id", "12345" },
                             { "screen_name", "twitterapi" },
                             { "include_entities", "true" },
                             { "include_ext_alt_text", "true" },
                             { "tweet_mode", "extended" },
-                        })
-                )
-                .ReturnsAsync(LazyJson.Create(new TwitterUser()));
+                    })
+            )
+            .ReturnsAsync(LazyJson.Create(new TwitterUser()));
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.ListsMembersDestroy(12345L, "twitterapi")
-                    .IgnoreResponse()
-                    .ConfigureAwait(false);
+            await twitterApi.ListsMembersDestroy(12345L, "twitterapi")
+                .IgnoreResponse()
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task DirectMessagesEventsList_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.GetAsync<TwitterMessageEventList>(
-                        new Uri("direct_messages/events/list.json", UriKind.Relative),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.GetAsync<TwitterMessageEventList>(
+                    new Uri("direct_messages/events/list.json", UriKind.Relative),
+                    new Dictionary<string, string> {
                             { "count", "50" },
                             { "cursor", "12345abcdefg" },
-                        },
-                        "/direct_messages/events/list")
-                )
-                .ReturnsAsync(new TwitterMessageEventList());
+                    },
+                    "/direct_messages/events/list")
+            )
+            .ReturnsAsync(new TwitterMessageEventList());
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.DirectMessagesEventsList(count: 50, cursor: "12345abcdefg")
-                    .ConfigureAwait(false);
+            await twitterApi.DirectMessagesEventsList(count: 50, cursor: "12345abcdefg")
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task DirectMessagesEventsNew_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.PostJsonAsync<TwitterMessageEventSingle>(
-                        new Uri("direct_messages/events/new.json", UriKind.Relative),
-                        @"{
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.PostJsonAsync<TwitterMessageEventSingle>(
+                    new Uri("direct_messages/events/new.json", UriKind.Relative),
+                    @"{
   ""event"": {
     ""type"": ""message_create"",
     ""message_create"": {
@@ -715,459 +669,424 @@ namespace OpenTween.Api
     }
   }
 }")
-                )
-                .ReturnsAsync(LazyJson.Create(new TwitterMessageEventSingle()));
+            )
+            .ReturnsAsync(LazyJson.Create(new TwitterMessageEventSingle()));
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.DirectMessagesEventsNew(recipientId: 12345L, text: "hogehoge", mediaId: 67890L)
-                    .ConfigureAwait(false);
+            await twitterApi.DirectMessagesEventsNew(recipientId: 12345L, text: "hogehoge", mediaId: 67890L)
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task DirectMessagesEventsDestroy_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.DeleteAsync(
-                        new Uri("direct_messages/events/destroy.json?id=100", UriKind.Relative))
-                )
-                .Returns(Task.CompletedTask);
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.DeleteAsync(
+                    new Uri("direct_messages/events/destroy.json?id=100", UriKind.Relative))
+            )
+            .Returns(Task.CompletedTask);
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.DirectMessagesEventsDestroy(eventId: "100")
-                    .ConfigureAwait(false);
+            await twitterApi.DirectMessagesEventsDestroy(eventId: "100")
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task UsersShow_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.GetAsync<TwitterUser>(
-                        new Uri("users/show.json", UriKind.Relative),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.GetAsync<TwitterUser>(
+                    new Uri("users/show.json", UriKind.Relative),
+                    new Dictionary<string, string> {
                             { "screen_name", "twitterapi" },
                             { "include_entities", "true" },
                             { "include_ext_alt_text", "true" },
                             { "tweet_mode", "extended" },
-                        },
-                        "/users/show/:id")
-                )
-                .ReturnsAsync(new TwitterUser { ScreenName = "twitterapi" });
+                    },
+                    "/users/show/:id")
+            )
+            .ReturnsAsync(new TwitterUser { ScreenName = "twitterapi" });
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.UsersShow(screenName: "twitterapi")
-                    .ConfigureAwait(false);
+            await twitterApi.UsersShow(screenName: "twitterapi")
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task UsersLookup_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.GetAsync<TwitterUser[]>(
-                        new Uri("users/lookup.json", UriKind.Relative),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.GetAsync<TwitterUser[]>(
+                    new Uri("users/lookup.json", UriKind.Relative),
+                    new Dictionary<string, string> {
                             { "user_id", "11111,22222" },
                             { "include_entities", "true" },
                             { "include_ext_alt_text", "true" },
                             { "tweet_mode", "extended" },
-                        },
-                        "/users/lookup")
-                )
-                .ReturnsAsync(Array.Empty<TwitterUser>());
+                    },
+                    "/users/lookup")
+            )
+            .ReturnsAsync(Array.Empty<TwitterUser>());
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.UsersLookup(userIds: new[] { "11111", "22222" })
-                    .ConfigureAwait(false);
+            await twitterApi.UsersLookup(userIds: new[] { "11111", "22222" })
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task UsersReportSpam_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.PostLazyAsync<TwitterUser>(
-                        new Uri("users/report_spam.json", UriKind.Relative),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.PostLazyAsync<TwitterUser>(
+                    new Uri("users/report_spam.json", UriKind.Relative),
+                    new Dictionary<string, string> {
                             { "screen_name", "twitterapi" },
                             { "tweet_mode", "extended" },
-                        })
-                )
-                .ReturnsAsync(LazyJson.Create(new TwitterUser { ScreenName = "twitterapi" }));
+                    })
+            )
+            .ReturnsAsync(LazyJson.Create(new TwitterUser { ScreenName = "twitterapi" }));
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.UsersReportSpam(screenName: "twitterapi")
-                    .IgnoreResponse()
-                    .ConfigureAwait(false);
+            await twitterApi.UsersReportSpam(screenName: "twitterapi")
+                .IgnoreResponse()
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task FavoritesList_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.GetAsync<TwitterStatus[]>(
-                        new Uri("favorites/list.json", UriKind.Relative),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.GetAsync<TwitterStatus[]>(
+                    new Uri("favorites/list.json", UriKind.Relative),
+                    new Dictionary<string, string> {
                             { "include_entities", "true" },
                             { "include_ext_alt_text", "true" },
                             { "tweet_mode", "extended" },
                             { "count", "200" },
                             { "max_id", "900" },
                             { "since_id", "100" },
-                        },
-                        "/favorites/list")
-                )
-                .ReturnsAsync(Array.Empty<TwitterStatus>());
+                    },
+                    "/favorites/list")
+            )
+            .ReturnsAsync(Array.Empty<TwitterStatus>());
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.FavoritesList(200, maxId: 900L, sinceId: 100L)
-                    .ConfigureAwait(false);
+            await twitterApi.FavoritesList(200, maxId: 900L, sinceId: 100L)
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task FavoritesCreate_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.PostLazyAsync<TwitterStatus>(
-                        new Uri("favorites/create.json", UriKind.Relative),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.PostLazyAsync<TwitterStatus>(
+                    new Uri("favorites/create.json", UriKind.Relative),
+                    new Dictionary<string, string> {
                             { "id", "100" },
                             { "tweet_mode", "extended" },
-                        })
-                )
-                .ReturnsAsync(LazyJson.Create(new TwitterStatus { Id = 100L }));
+                    })
+            )
+            .ReturnsAsync(LazyJson.Create(new TwitterStatus { Id = 100L }));
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.FavoritesCreate(statusId: 100L)
-                    .IgnoreResponse()
-                    .ConfigureAwait(false);
+            await twitterApi.FavoritesCreate(statusId: 100L)
+                .IgnoreResponse()
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task FavoritesDestroy_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.PostLazyAsync<TwitterStatus>(
-                        new Uri("favorites/destroy.json", UriKind.Relative),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.PostLazyAsync<TwitterStatus>(
+                    new Uri("favorites/destroy.json", UriKind.Relative),
+                    new Dictionary<string, string> {
                             { "id", "100" },
                             { "tweet_mode", "extended" },
-                        })
-                )
-                .ReturnsAsync(LazyJson.Create(new TwitterStatus { Id = 100L }));
+                    })
+            )
+            .ReturnsAsync(LazyJson.Create(new TwitterStatus { Id = 100L }));
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.FavoritesDestroy(statusId: 100L)
-                    .IgnoreResponse()
-                    .ConfigureAwait(false);
+            await twitterApi.FavoritesDestroy(statusId: 100L)
+                .IgnoreResponse()
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task FriendshipsShow_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.GetAsync<TwitterFriendship>(
-                        new Uri("friendships/show.json", UriKind.Relative),
-                        new Dictionary<string, string> { { "source_screen_name", "twitter" }, { "target_screen_name", "twitterapi" } },
-                        "/friendships/show")
-                )
-                .ReturnsAsync(new TwitterFriendship());
-
-                twitterApi.apiConnection = mock.Object;
-
-                await twitterApi.FriendshipsShow(sourceScreenName: "twitter", targetScreenName: "twitterapi")
-                    .ConfigureAwait(false);
-
-                mock.VerifyAll();
-            }
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.GetAsync<TwitterFriendship>(
+                    new Uri("friendships/show.json", UriKind.Relative),
+                    new Dictionary<string, string> { { "source_screen_name", "twitter" }, { "target_screen_name", "twitterapi" } },
+                    "/friendships/show")
+            )
+            .ReturnsAsync(new TwitterFriendship());
+
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
+
+            await twitterApi.FriendshipsShow(sourceScreenName: "twitter", targetScreenName: "twitterapi")
+                .ConfigureAwait(false);
+
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task FriendshipsCreate_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.PostLazyAsync<TwitterFriendship>(
-                        new Uri("friendships/create.json", UriKind.Relative),
-                        new Dictionary<string, string> { { "screen_name", "twitterapi" } })
-                )
-                .ReturnsAsync(LazyJson.Create(new TwitterFriendship()));
-
-                twitterApi.apiConnection = mock.Object;
-
-                await twitterApi.FriendshipsCreate(screenName: "twitterapi")
-                    .IgnoreResponse()
-                    .ConfigureAwait(false);
-
-                mock.VerifyAll();
-            }
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.PostLazyAsync<TwitterFriendship>(
+                    new Uri("friendships/create.json", UriKind.Relative),
+                    new Dictionary<string, string> { { "screen_name", "twitterapi" } })
+            )
+            .ReturnsAsync(LazyJson.Create(new TwitterFriendship()));
+
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
+
+            await twitterApi.FriendshipsCreate(screenName: "twitterapi")
+                .IgnoreResponse()
+                .ConfigureAwait(false);
+
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task FriendshipsDestroy_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.PostLazyAsync<TwitterFriendship>(
-                        new Uri("friendships/destroy.json", UriKind.Relative),
-                        new Dictionary<string, string> { { "screen_name", "twitterapi" } })
-                )
-                .ReturnsAsync(LazyJson.Create(new TwitterFriendship()));
-
-                twitterApi.apiConnection = mock.Object;
-
-                await twitterApi.FriendshipsDestroy(screenName: "twitterapi")
-                    .IgnoreResponse()
-                    .ConfigureAwait(false);
-
-                mock.VerifyAll();
-            }
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.PostLazyAsync<TwitterFriendship>(
+                    new Uri("friendships/destroy.json", UriKind.Relative),
+                    new Dictionary<string, string> { { "screen_name", "twitterapi" } })
+            )
+            .ReturnsAsync(LazyJson.Create(new TwitterFriendship()));
+
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
+
+            await twitterApi.FriendshipsDestroy(screenName: "twitterapi")
+                .IgnoreResponse()
+                .ConfigureAwait(false);
+
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task NoRetweetIds_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.GetAsync<long[]>(
-                        new Uri("friendships/no_retweets/ids.json", UriKind.Relative),
-                        null,
-                        "/friendships/no_retweets/ids")
-                )
-                .ReturnsAsync(Array.Empty<long>());
-
-                twitterApi.apiConnection = mock.Object;
-
-                await twitterApi.NoRetweetIds()
-                    .ConfigureAwait(false);
-
-                mock.VerifyAll();
-            }
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.GetAsync<long[]>(
+                    new Uri("friendships/no_retweets/ids.json", UriKind.Relative),
+                    null,
+                    "/friendships/no_retweets/ids")
+            )
+            .ReturnsAsync(Array.Empty<long>());
+
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
+
+            await twitterApi.NoRetweetIds()
+                .ConfigureAwait(false);
+
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task FollowersIds_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.GetAsync<TwitterIds>(
-                        new Uri("followers/ids.json", UriKind.Relative),
-                        new Dictionary<string, string> { { "cursor", "-1" } },
-                        "/followers/ids")
-                )
-                .ReturnsAsync(new TwitterIds());
-
-                twitterApi.apiConnection = mock.Object;
-
-                await twitterApi.FollowersIds(cursor: -1L)
-                    .ConfigureAwait(false);
-
-                mock.VerifyAll();
-            }
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.GetAsync<TwitterIds>(
+                    new Uri("followers/ids.json", UriKind.Relative),
+                    new Dictionary<string, string> { { "cursor", "-1" } },
+                    "/followers/ids")
+            )
+            .ReturnsAsync(new TwitterIds());
+
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
+
+            await twitterApi.FollowersIds(cursor: -1L)
+                .ConfigureAwait(false);
+
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task MutesUsersIds_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.GetAsync<TwitterIds>(
-                        new Uri("mutes/users/ids.json", UriKind.Relative),
-                        new Dictionary<string, string> { { "cursor", "-1" } },
-                        "/mutes/users/ids")
-                )
-                .ReturnsAsync(new TwitterIds());
-
-                twitterApi.apiConnection = mock.Object;
-
-                await twitterApi.MutesUsersIds(cursor: -1L)
-                    .ConfigureAwait(false);
-
-                mock.VerifyAll();
-            }
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.GetAsync<TwitterIds>(
+                    new Uri("mutes/users/ids.json", UriKind.Relative),
+                    new Dictionary<string, string> { { "cursor", "-1" } },
+                    "/mutes/users/ids")
+            )
+            .ReturnsAsync(new TwitterIds());
+
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
+
+            await twitterApi.MutesUsersIds(cursor: -1L)
+                .ConfigureAwait(false);
+
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task BlocksIds_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.GetAsync<TwitterIds>(
-                        new Uri("blocks/ids.json", UriKind.Relative),
-                        new Dictionary<string, string> { { "cursor", "-1" } },
-                        "/blocks/ids")
-                )
-                .ReturnsAsync(new TwitterIds());
-
-                twitterApi.apiConnection = mock.Object;
-
-                await twitterApi.BlocksIds(cursor: -1L)
-                    .ConfigureAwait(false);
-
-                mock.VerifyAll();
-            }
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.GetAsync<TwitterIds>(
+                    new Uri("blocks/ids.json", UriKind.Relative),
+                    new Dictionary<string, string> { { "cursor", "-1" } },
+                    "/blocks/ids")
+            )
+            .ReturnsAsync(new TwitterIds());
+
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
+
+            await twitterApi.BlocksIds(cursor: -1L)
+                .ConfigureAwait(false);
+
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task BlocksCreate_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.PostLazyAsync<TwitterUser>(
-                        new Uri("blocks/create.json", UriKind.Relative),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.PostLazyAsync<TwitterUser>(
+                    new Uri("blocks/create.json", UriKind.Relative),
+                    new Dictionary<string, string> {
                             { "screen_name", "twitterapi" },
                             { "tweet_mode", "extended" },
-                        })
-                )
-                .ReturnsAsync(LazyJson.Create(new TwitterUser()));
+                    })
+            )
+            .ReturnsAsync(LazyJson.Create(new TwitterUser()));
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.BlocksCreate(screenName: "twitterapi")
-                    .IgnoreResponse()
-                    .ConfigureAwait(false);
+            await twitterApi.BlocksCreate(screenName: "twitterapi")
+                .IgnoreResponse()
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task BlocksDestroy_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.PostLazyAsync<TwitterUser>(
-                        new Uri("blocks/destroy.json", UriKind.Relative),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.PostLazyAsync<TwitterUser>(
+                    new Uri("blocks/destroy.json", UriKind.Relative),
+                    new Dictionary<string, string> {
                             { "screen_name", "twitterapi" },
                             { "tweet_mode", "extended" },
-                        })
-                )
-                .ReturnsAsync(LazyJson.Create(new TwitterUser()));
+                    })
+            )
+            .ReturnsAsync(LazyJson.Create(new TwitterUser()));
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.BlocksDestroy(screenName: "twitterapi")
-                    .IgnoreResponse()
-                    .ConfigureAwait(false);
+            await twitterApi.BlocksDestroy(screenName: "twitterapi")
+                .IgnoreResponse()
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task AccountVerifyCredentials_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.GetAsync<TwitterUser>(
-                        new Uri("account/verify_credentials.json", UriKind.Relative),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.GetAsync<TwitterUser>(
+                    new Uri("account/verify_credentials.json", UriKind.Relative),
+                    new Dictionary<string, string> {
                             { "include_entities", "true" },
                             { "include_ext_alt_text", "true" },
                             { "tweet_mode", "extended" },
-                        },
-                        "/account/verify_credentials")
-                )
-                .ReturnsAsync(new TwitterUser {
-                    Id = 100L,
-                    ScreenName = "opentween",
-                });
+                    },
+                    "/account/verify_credentials")
+            )
+            .ReturnsAsync(new TwitterUser
+            {
+                Id = 100L,
+                ScreenName = "opentween",
+            });
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.AccountVerifyCredentials()
-                    .ConfigureAwait(false);
+            await twitterApi.AccountVerifyCredentials()
+                .ConfigureAwait(false);
 
-                Assert.Equal(100L, twitterApi.CurrentUserId);
-                Assert.Equal("opentween", twitterApi.CurrentScreenName);
+            Assert.Equal(100L, twitterApi.CurrentUserId);
+            Assert.Equal("opentween", twitterApi.CurrentScreenName);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task AccountUpdateProfile_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.PostLazyAsync<TwitterUser>(
-                        new Uri("account/update_profile.json", UriKind.Relative),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.PostLazyAsync<TwitterUser>(
+                    new Uri("account/update_profile.json", UriKind.Relative),
+                    new Dictionary<string, string> {
                             { "include_entities", "true" },
                             { "include_ext_alt_text", "true" },
                             { "tweet_mode", "extended" },
@@ -1175,250 +1094,232 @@ namespace OpenTween.Api
                             { "url", "http://example.com/" },
                             { "location", "Location" },
                             { "description", "&lt;script&gt;alert(1)&lt;/script&gt;" },
-                        })
-                )
-                .ReturnsAsync(LazyJson.Create(new TwitterUser()));
+                    })
+            )
+            .ReturnsAsync(LazyJson.Create(new TwitterUser()));
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.AccountUpdateProfile(name: "Name", url: "http://example.com/", location: "Location", description: "<script>alert(1)</script>")
-                    .IgnoreResponse()
-                    .ConfigureAwait(false);
+            await twitterApi.AccountUpdateProfile(name: "Name", url: "http://example.com/", location: "Location", description: "<script>alert(1)</script>")
+                .IgnoreResponse()
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task AccountUpdateProfileImage_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            using (var image = TestUtils.CreateDummyImage())
-            using (var media = new MemoryImageMediaItem(image))
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.PostLazyAsync<TwitterUser>(
-                        new Uri("account/update_profile_image.json", UriKind.Relative),
-                        new Dictionary<string, string> {
+            using var image = TestUtils.CreateDummyImage();
+            using var media = new MemoryImageMediaItem(image);
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.PostLazyAsync<TwitterUser>(
+                    new Uri("account/update_profile_image.json", UriKind.Relative),
+                    new Dictionary<string, string> {
                             { "include_entities", "true" },
                             { "include_ext_alt_text", "true" },
                             { "tweet_mode", "extended" },
-                        },
-                        new Dictionary<string, IMediaItem> { { "image", media } })
-                )
-                .ReturnsAsync(LazyJson.Create(new TwitterUser()));
+                    },
+                    new Dictionary<string, IMediaItem> { { "image", media } })
+            )
+            .ReturnsAsync(LazyJson.Create(new TwitterUser()));
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.AccountUpdateProfileImage(media)
-                    .IgnoreResponse()
-                    .ConfigureAwait(false);
+            await twitterApi.AccountUpdateProfileImage(media)
+                .IgnoreResponse()
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task ApplicationRateLimitStatus_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.GetAsync<TwitterRateLimits>(
-                        new Uri("application/rate_limit_status.json", UriKind.Relative),
-                        null,
-                        "/application/rate_limit_status")
-                )
-                .ReturnsAsync(new TwitterRateLimits());
-
-                twitterApi.apiConnection = mock.Object;
-
-                await twitterApi.ApplicationRateLimitStatus()
-                    .ConfigureAwait(false);
-
-                mock.VerifyAll();
-            }
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.GetAsync<TwitterRateLimits>(
+                    new Uri("application/rate_limit_status.json", UriKind.Relative),
+                    null,
+                    "/application/rate_limit_status")
+            )
+            .ReturnsAsync(new TwitterRateLimits());
+
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
+
+            await twitterApi.ApplicationRateLimitStatus()
+                .ConfigureAwait(false);
+
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task Configuration_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.GetAsync<TwitterConfiguration>(
-                        new Uri("help/configuration.json", UriKind.Relative),
-                        null,
-                        "/help/configuration")
-                )
-                .ReturnsAsync(new TwitterConfiguration());
-
-                twitterApi.apiConnection = mock.Object;
-
-                await twitterApi.Configuration()
-                    .ConfigureAwait(false);
-
-                mock.VerifyAll();
-            }
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.GetAsync<TwitterConfiguration>(
+                    new Uri("help/configuration.json", UriKind.Relative),
+                    null,
+                    "/help/configuration")
+            )
+            .ReturnsAsync(new TwitterConfiguration());
+
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
+
+            await twitterApi.Configuration()
+                .ConfigureAwait(false);
+
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task MediaUploadInit_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.PostLazyAsync<TwitterUploadMediaInit>(
-                        new Uri("https://upload.twitter.com/1.1/media/upload.json", UriKind.Absolute),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.PostLazyAsync<TwitterUploadMediaInit>(
+                    new Uri("https://upload.twitter.com/1.1/media/upload.json", UriKind.Absolute),
+                    new Dictionary<string, string> {
                             { "command", "INIT" },
                             { "total_bytes", "123456" },
                             { "media_type", "image/png" },
                             { "media_category", "dm_image" },
-                        })
-                )
-                .ReturnsAsync(LazyJson.Create(new TwitterUploadMediaInit()));
+                    })
+            )
+            .ReturnsAsync(LazyJson.Create(new TwitterUploadMediaInit()));
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.MediaUploadInit(totalBytes: 123456L, mediaType: "image/png", mediaCategory: "dm_image")
-                    .IgnoreResponse()
-                    .ConfigureAwait(false);
+            await twitterApi.MediaUploadInit(totalBytes: 123456L, mediaType: "image/png", mediaCategory: "dm_image")
+                .IgnoreResponse()
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task MediaUploadAppend_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            using (var image = TestUtils.CreateDummyImage())
-            using (var media = new MemoryImageMediaItem(image))
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.PostAsync(
-                        new Uri("https://upload.twitter.com/1.1/media/upload.json", UriKind.Absolute),
-                        new Dictionary<string, string> {
+            using var image = TestUtils.CreateDummyImage();
+            using var media = new MemoryImageMediaItem(image);
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.PostAsync(
+                    new Uri("https://upload.twitter.com/1.1/media/upload.json", UriKind.Absolute),
+                    new Dictionary<string, string> {
                             { "command", "APPEND" },
                             { "media_id", "11111" },
                             { "segment_index", "1" },
-                        },
-                        new Dictionary<string, IMediaItem> { { "media", media } })
-                )
-                .Returns(Task.CompletedTask);
+                    },
+                    new Dictionary<string, IMediaItem> { { "media", media } })
+            )
+            .Returns(Task.CompletedTask);
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.MediaUploadAppend(mediaId: 11111L, segmentIndex: 1, media: media)
-                    .ConfigureAwait(false);
+            await twitterApi.MediaUploadAppend(mediaId: 11111L, segmentIndex: 1, media: media)
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task MediaUploadFinalize_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.PostLazyAsync<TwitterUploadMediaResult>(
-                        new Uri("https://upload.twitter.com/1.1/media/upload.json", UriKind.Absolute),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.PostLazyAsync<TwitterUploadMediaResult>(
+                    new Uri("https://upload.twitter.com/1.1/media/upload.json", UriKind.Absolute),
+                    new Dictionary<string, string> {
                             { "command", "FINALIZE" },
                             { "media_id", "11111" },
-                        })
-                )
-                .ReturnsAsync(LazyJson.Create(new TwitterUploadMediaResult()));
+                    })
+            )
+            .ReturnsAsync(LazyJson.Create(new TwitterUploadMediaResult()));
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.MediaUploadFinalize(mediaId: 11111L)
-                    .IgnoreResponse()
-                    .ConfigureAwait(false);
+            await twitterApi.MediaUploadFinalize(mediaId: 11111L)
+                .IgnoreResponse()
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task MediaUploadStatus_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.GetAsync<TwitterUploadMediaResult>(
-                        new Uri("https://upload.twitter.com/1.1/media/upload.json", UriKind.Absolute),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.GetAsync<TwitterUploadMediaResult>(
+                    new Uri("https://upload.twitter.com/1.1/media/upload.json", UriKind.Absolute),
+                    new Dictionary<string, string> {
                             { "command", "STATUS" },
                             { "media_id", "11111" },
-                        },
-                        null)
-                )
-                .ReturnsAsync(new TwitterUploadMediaResult());
+                    },
+                    null)
+            )
+            .ReturnsAsync(new TwitterUploadMediaResult());
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.MediaUploadStatus(mediaId: 11111L)
-                    .ConfigureAwait(false);
+            await twitterApi.MediaUploadStatus(mediaId: 11111L)
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task MediaMetadataCreate_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.PostJsonAsync(
-                        new Uri("https://upload.twitter.com/1.1/media/metadata/create.json", UriKind.Absolute),
-                        "{\"media_id\": \"12345\", \"alt_text\": {\"text\": \"hogehoge\"}}")
-                )
-                .Returns(Task.CompletedTask);
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.PostJsonAsync(
+                    new Uri("https://upload.twitter.com/1.1/media/metadata/create.json", UriKind.Absolute),
+                    "{\"media_id\": \"12345\", \"alt_text\": {\"text\": \"hogehoge\"}}")
+            )
+            .Returns(Task.CompletedTask);
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                await twitterApi.MediaMetadataCreate(mediaId: 12345L, altText: "hogehoge")
-                    .ConfigureAwait(false);
+            await twitterApi.MediaMetadataCreate(mediaId: 12345L, altText: "hogehoge")
+                .ConfigureAwait(false);
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
 
         [Fact]
         public async Task UserStreams_Test()
         {
-            using (var twitterApi = new TwitterApi())
-            {
-                var mock = new Mock<IApiConnection>();
-                mock.Setup(x =>
-                    x.GetStreamingStreamAsync(
-                        new Uri("https://userstream.twitter.com/1.1/user.json", UriKind.Absolute),
-                        new Dictionary<string, string> {
+            var mock = new Mock<IApiConnection>();
+            mock.Setup(x =>
+                x.GetStreamingStreamAsync(
+                    new Uri("https://userstream.twitter.com/1.1/user.json", UriKind.Absolute),
+                    new Dictionary<string, string> {
                             { "replies", "all" },
                             { "track", "OpenTween" },
-                        })
-                )
-                .ReturnsAsync(new MemoryStream());
+                    })
+            )
+            .ReturnsAsync(new MemoryStream());
 
-                twitterApi.apiConnection = mock.Object;
+            using var twitterApi = new TwitterApi();
+            twitterApi.apiConnection = mock.Object;
 
-                var observable = twitterApi.UserStreams(replies: "all", track: "OpenTween");
-                await observable.ForEachAsync(x => { });
+            var observable = twitterApi.UserStreams(replies: "all", track: "OpenTween");
+            await observable.ForEachAsync(x => { });
 
-                mock.VerifyAll();
-            }
+            mock.VerifyAll();
         }
     }
 }
index bb30d1c..242797f 100644 (file)
@@ -38,66 +38,58 @@ namespace OpenTween.Connection
         public async Task LoadJsonAsync_Test()
         {
             var body = Encoding.UTF8.GetBytes("\"hogehoge\"");
-            using (var bodyStream = new MemoryStream(body))
-            using (var response = new HttpResponseMessage())
-            {
-                response.Content = new StreamContent(bodyStream);
+            using var bodyStream = new MemoryStream(body);
+            using var response = new HttpResponseMessage();
+            response.Content = new StreamContent(bodyStream);
 
-                using (var lazyJson = new LazyJson<string>(response))
-                {
-                    // この時点ではまだレスポンスボディは読まれない
-                    Assert.Equal(0, bodyStream.Position);
+            using var lazyJson = new LazyJson<string>(response);
 
-                    var result = await lazyJson.LoadJsonAsync()
-                        .ConfigureAwait(false);
+            // この時点ではまだレスポンスボディは読まれない
+            Assert.Equal(0, bodyStream.Position);
 
-                    Assert.Equal("hogehoge", result);
-                }
-            }
+            var result = await lazyJson.LoadJsonAsync()
+                .ConfigureAwait(false);
+
+            Assert.Equal("hogehoge", result);
         }
 
         [Fact]
         public async Task LoadJsonAsync_InvalidJsonTest()
         {
             var body = Encoding.UTF8.GetBytes("### Invalid JSON ###");
-            using (var bodyStream = new MemoryStream(body))
-            using (var response = new HttpResponseMessage())
-            {
-                response.Content = new StreamContent(bodyStream);
+            using var bodyStream = new MemoryStream(body);
+            using var response = new HttpResponseMessage();
+            response.Content = new StreamContent(bodyStream);
 
-                using (var lazyJson = new LazyJson<string>(response))
-                {
-                    // この時点ではまだレスポンスボディは読まれない
-                    Assert.Equal(0, bodyStream.Position);
+            using var lazyJson = new LazyJson<string>(response);
 
-                    var exception = await Assert.ThrowsAnyAsync<WebApiException>(() => lazyJson.LoadJsonAsync())
-                        .ConfigureAwait(false);
+            // この時点ではまだレスポンスボディは読まれない
+            Assert.Equal(0, bodyStream.Position);
 
-                    Assert.IsType<SerializationException>(exception.InnerException);
-                }
-            }
+            var exception = await Assert.ThrowsAnyAsync<WebApiException>(() => lazyJson.LoadJsonAsync())
+                .ConfigureAwait(false);
+
+            Assert.IsType<SerializationException>(exception.InnerException);
         }
 
         [Fact]
         public async Task IgnoreResponse_Test()
         {
-            using (var bodyStream = new InvalidStream())
-            using (var response = new HttpResponseMessage())
-            {
-                // IgnoreResponse() によってレスポンスの Stream が読まれずに破棄されることをテストするため、
-                // 読み込みが行われると IOException が発生する InvalidStream クラスを bodyStream に使用している
-                response.Content = new StreamContent(bodyStream);
-
-                using (var lazyJson = new LazyJson<string>(response))
-                {
-                    // レスポンスボディを読まずに破棄
-                    await Task.FromResult(lazyJson)
-                        .IgnoreResponse()
-                        .ConfigureAwait(false);
-
-                    Assert.True(bodyStream.IsDisposed);
-                }
-            }
+            using var bodyStream = new InvalidStream();
+            using var response = new HttpResponseMessage();
+
+            // IgnoreResponse() によってレスポンスの Stream が読まれずに破棄されることをテストするため、
+            // 読み込みが行われると IOException が発生する InvalidStream クラスを bodyStream に使用している
+            response.Content = new StreamContent(bodyStream);
+
+            using var lazyJson = new LazyJson<string>(response);
+
+            // レスポンスボディを読まずに破棄
+            await Task.FromResult(lazyJson)
+                .IgnoreResponse()
+                .ConfigureAwait(false);
+
+            Assert.True(bodyStream.IsDisposed);
         }
 
         class InvalidStream : Stream
index da0e34f..51dd44d 100644 (file)
@@ -57,18 +57,17 @@ namespace OpenTween.Connection
                 new KeyValuePair<string, string>("bbb", "2"),
             };
 
-            using (var content = new FormUrlEncodedContent(formParams))
+            using var content = new FormUrlEncodedContent(formParams);
+            var actual = await OAuthHandler.GetParameters(requestUri, content)
+                .ConfigureAwait(false);
+
+            var expected = new[]
             {
-                var actual = await OAuthHandler.GetParameters(requestUri, content)
-                    .ConfigureAwait(false);
-                var expected = new[]
-                {
-                    new KeyValuePair<string, string>("aaa", "1"),
-                    new KeyValuePair<string, string>("bbb", "2"),
-                };
+                new KeyValuePair<string, string>("aaa", "1"),
+                new KeyValuePair<string, string>("bbb", "2"),
+            };
 
-                Assert.Equal(expected, actual);
-            }
+            Assert.Equal(expected, actual);
         }
 
         [Fact]
@@ -76,19 +75,17 @@ namespace OpenTween.Connection
         {
             var requestUri = new Uri("http://example.com/api");
 
-            using (var content = new MultipartFormDataContent())
-            using (var paramA = new StringContent("1"))
-            using (var paramB = new StringContent("2"))
-            {
-                content.Add(paramA, "aaa");
-                content.Add(paramB, "bbb");
+            using var content = new MultipartFormDataContent();
+            using var paramA = new StringContent("1");
+            using var paramB = new StringContent("2");
+            content.Add(paramA, "aaa");
+            content.Add(paramB, "bbb");
 
-                var actual = await OAuthHandler.GetParameters(requestUri, content)
-                    .ConfigureAwait(false);
+            var actual = await OAuthHandler.GetParameters(requestUri, content)
+                .ConfigureAwait(false);
 
-                // multipart/form-data のリクエストではパラメータを署名対象にしない
-                Assert.Empty(actual);
-            }
+            // multipart/form-data のリクエストではパラメータを署名対象にしない
+            Assert.Empty(actual);
         }
     }
 }
index d26908d..2328ae6 100644 (file)
@@ -59,11 +59,9 @@ namespace OpenTween.Connection
             var expectSignatureBase = "GET&http%3A%2F%2Fexample.com%2Fhoge&aaa%3Dfoo";
             var expectSignatureKey = "ConsumerSecret&TokenSecret";
 
-            using (var hmacsha1 = new HMACSHA1(Encoding.ASCII.GetBytes(expectSignatureKey)))
-            {
-                var expectSignature = Convert.ToBase64String(hmacsha1.ComputeHash(Encoding.ASCII.GetBytes(expectSignatureBase)));
-                Assert.Equal(expectSignature, oauthSignature);
-            }
+            using var hmacsha1 = new HMACSHA1(Encoding.ASCII.GetBytes(expectSignatureKey));
+            var expectSignature = Convert.ToBase64String(hmacsha1.ComputeHash(Encoding.ASCII.GetBytes(expectSignatureBase)));
+            Assert.Equal(expectSignature, oauthSignature);
         }
 
         [Fact]
@@ -80,11 +78,9 @@ namespace OpenTween.Connection
             var expectSignatureBase = "GET&http%3A%2F%2Fexample.com%2Fhoge&aaa%3Dfoo%26bbb%3Dbar";
             var expectSignatureKey = "ConsumerSecret&TokenSecret";
 
-            using (var hmacsha1 = new HMACSHA1(Encoding.ASCII.GetBytes(expectSignatureKey)))
-            {
-                var expectSignature = Convert.ToBase64String(hmacsha1.ComputeHash(Encoding.ASCII.GetBytes(expectSignatureBase)));
-                Assert.Equal(expectSignature, oauthSignature);
-            }
+            using var hmacsha1 = new HMACSHA1(Encoding.ASCII.GetBytes(expectSignatureKey));
+            var expectSignature = Convert.ToBase64String(hmacsha1.ComputeHash(Encoding.ASCII.GetBytes(expectSignatureBase)));
+            Assert.Equal(expectSignature, oauthSignature);
         }
 
         [Fact]
@@ -98,11 +94,9 @@ namespace OpenTween.Connection
             var expectSignatureBase = "GET&http%3A%2F%2Fexample.com%2Fhoge&aaa%3Dfoo";
             var expectSignatureKey = "ConsumerSecret&"; // 末尾の & は除去されない
 
-            using (var hmacsha1 = new HMACSHA1(Encoding.ASCII.GetBytes(expectSignatureKey)))
-            {
-                var expectSignature = Convert.ToBase64String(hmacsha1.ComputeHash(Encoding.ASCII.GetBytes(expectSignatureBase)));
-                Assert.Equal(expectSignature, oauthSignature);
-            }
+            using var hmacsha1 = new HMACSHA1(Encoding.ASCII.GetBytes(expectSignatureKey));
+            var expectSignature = Convert.ToBase64String(hmacsha1.ComputeHash(Encoding.ASCII.GetBytes(expectSignatureBase)));
+            Assert.Equal(expectSignature, oauthSignature);
         }
 
         [Fact]
@@ -137,11 +131,9 @@ namespace OpenTween.Connection
 
             var expectSignatureKey = "ConsumerSecret&AccessSecret";
 
-            using (var hmacsha1 = new HMACSHA1(Encoding.ASCII.GetBytes(expectSignatureKey)))
-            {
-                var expectSignature = Convert.ToBase64String(hmacsha1.ComputeHash(Encoding.ASCII.GetBytes(expectSignatureBase)));
-                Assert.Equal(expectSignature, Uri.UnescapeDataString(parsedParams["oauth_signature"]));
-            }
+            using var hmacsha1 = new HMACSHA1(Encoding.ASCII.GetBytes(expectSignatureKey));
+            var expectSignature = Convert.ToBase64String(hmacsha1.ComputeHash(Encoding.ASCII.GetBytes(expectSignatureBase)));
+            Assert.Equal(expectSignature, Uri.UnescapeDataString(parsedParams["oauth_signature"]));
         }
     }
 }
index 6fbff58..dd344b0 100644 (file)
@@ -54,508 +54,483 @@ namespace OpenTween.Connection
         [Fact]
         public async Task GetAsync_Test()
         {
-            using (var mockHandler = new HttpMessageHandlerMock())
-            using (var http = new HttpClient(mockHandler))
-            using (var apiConnection = new TwitterApiConnection("", ""))
-            {
-                apiConnection.http = http;
+            using var mockHandler = new HttpMessageHandlerMock();
+            using var http = new HttpClient(mockHandler);
+            using var apiConnection = new TwitterApiConnection("", "");
+            apiConnection.http = http;
 
-                mockHandler.Enqueue(x =>
-                {
-                    Assert.Equal(HttpMethod.Get, x.Method);
-                    Assert.Equal("https://api.twitter.com/1.1/hoge/tetete.json",
-                        x.RequestUri.GetLeftPart(UriPartial.Path));
+            mockHandler.Enqueue(x =>
+            {
+                Assert.Equal(HttpMethod.Get, x.Method);
+                Assert.Equal("https://api.twitter.com/1.1/hoge/tetete.json",
+                    x.RequestUri.GetLeftPart(UriPartial.Path));
 
-                    var query = HttpUtility.ParseQueryString(x.RequestUri.Query);
+                var query = HttpUtility.ParseQueryString(x.RequestUri.Query);
 
-                    Assert.Equal("1111", query["aaaa"]);
-                    Assert.Equal("2222", query["bbbb"]);
+                Assert.Equal("1111", query["aaaa"]);
+                Assert.Equal("2222", query["bbbb"]);
 
-                    return new HttpResponseMessage(HttpStatusCode.OK)
-                    {
-                        Content = new StringContent("\"hogehoge\""),
-                    };
-                });
-
-                var endpoint = new Uri("hoge/tetete.json", UriKind.Relative);
-                var param = new Dictionary<string, string>
+                return new HttpResponseMessage(HttpStatusCode.OK)
                 {
-                    ["aaaa"] = "1111",
-                    ["bbbb"] = "2222",
+                    Content = new StringContent("\"hogehoge\""),
                 };
+            });
 
-                var result = await apiConnection.GetAsync<string>(endpoint, param, endpointName: "/hoge/tetete")
-                    .ConfigureAwait(false);
-                Assert.Equal("hogehoge", result);
+            var endpoint = new Uri("hoge/tetete.json", UriKind.Relative);
+            var param = new Dictionary<string, string>
+            {
+                ["aaaa"] = "1111",
+                ["bbbb"] = "2222",
+            };
 
-                Assert.Equal(0, mockHandler.QueueCount);
-            }
+            var result = await apiConnection.GetAsync<string>(endpoint, param, endpointName: "/hoge/tetete")
+                .ConfigureAwait(false);
+            Assert.Equal("hogehoge", result);
+
+            Assert.Equal(0, mockHandler.QueueCount);
         }
 
         [Fact]
         public async Task GetAsync_AbsoluteUriTest()
         {
-            using (var mockHandler = new HttpMessageHandlerMock())
-            using (var http = new HttpClient(mockHandler))
-            using (var apiConnection = new TwitterApiConnection("", ""))
-            {
-                apiConnection.http = http;
+            using var mockHandler = new HttpMessageHandlerMock();
+            using var http = new HttpClient(mockHandler);
+            using var apiConnection = new TwitterApiConnection("", "");
+            apiConnection.http = http;
 
-                mockHandler.Enqueue(x =>
-                {
-                    Assert.Equal(HttpMethod.Get, x.Method);
-                    Assert.Equal("http://example.com/hoge/tetete.json",
-                        x.RequestUri.GetLeftPart(UriPartial.Path));
+            mockHandler.Enqueue(x =>
+            {
+                Assert.Equal(HttpMethod.Get, x.Method);
+                Assert.Equal("http://example.com/hoge/tetete.json",
+                    x.RequestUri.GetLeftPart(UriPartial.Path));
 
-                    var query = HttpUtility.ParseQueryString(x.RequestUri.Query);
+                var query = HttpUtility.ParseQueryString(x.RequestUri.Query);
 
-                    Assert.Equal("1111", query["aaaa"]);
-                    Assert.Equal("2222", query["bbbb"]);
+                Assert.Equal("1111", query["aaaa"]);
+                Assert.Equal("2222", query["bbbb"]);
 
-                    return new HttpResponseMessage(HttpStatusCode.OK)
-                    {
-                        Content = new StringContent("\"hogehoge\""),
-                    };
-                });
-
-                var endpoint = new Uri("http://example.com/hoge/tetete.json", UriKind.Absolute);
-                var param = new Dictionary<string, string>
+                return new HttpResponseMessage(HttpStatusCode.OK)
                 {
-                    ["aaaa"] = "1111",
-                    ["bbbb"] = "2222",
+                    Content = new StringContent("\"hogehoge\""),
                 };
+            });
 
-                await apiConnection.GetAsync<string>(endpoint, param, endpointName: "/hoge/tetete")
-                    .ConfigureAwait(false);
+            var endpoint = new Uri("http://example.com/hoge/tetete.json", UriKind.Absolute);
+            var param = new Dictionary<string, string>
+            {
+                ["aaaa"] = "1111",
+                ["bbbb"] = "2222",
+            };
 
-                Assert.Equal(0, mockHandler.QueueCount);
-            }
+            await apiConnection.GetAsync<string>(endpoint, param, endpointName: "/hoge/tetete")
+                .ConfigureAwait(false);
+
+            Assert.Equal(0, mockHandler.QueueCount);
         }
 
         [Fact]
         public async Task GetAsync_UpdateRateLimitTest()
         {
-            using (var mockHandler = new HttpMessageHandlerMock())
-            using (var http = new HttpClient(mockHandler))
-            using (var apiConnection = new TwitterApiConnection("", ""))
+            using var mockHandler = new HttpMessageHandlerMock();
+            using var http = new HttpClient(mockHandler);
+            using var apiConnection = new TwitterApiConnection("", "");
+            apiConnection.http = http;
+
+            mockHandler.Enqueue(x =>
             {
-                apiConnection.http = http;
+                Assert.Equal(HttpMethod.Get, x.Method);
+                Assert.Equal("https://api.twitter.com/1.1/hoge/tetete.json",
+                    x.RequestUri.GetLeftPart(UriPartial.Path));
 
-                mockHandler.Enqueue(x =>
+                return new HttpResponseMessage(HttpStatusCode.OK)
                 {
-                    Assert.Equal(HttpMethod.Get, x.Method);
-                    Assert.Equal("https://api.twitter.com/1.1/hoge/tetete.json",
-                        x.RequestUri.GetLeftPart(UriPartial.Path));
-
-                    return new HttpResponseMessage(HttpStatusCode.OK)
+                    Headers =
                     {
-                        Headers =
-                        {
                             { "X-Rate-Limit-Limit", "150" },
                             { "X-Rate-Limit-Remaining", "100" },
                             { "X-Rate-Limit-Reset", "1356998400" },
                             { "X-Access-Level", "read-write-directmessages" },
-                        },
-                        Content = new StringContent("\"hogehoge\""),
-                    };
-                });
+                    },
+                    Content = new StringContent("\"hogehoge\""),
+                };
+            });
 
-                var apiStatus = new TwitterApiStatus();
-                MyCommon.TwitterApiInfo = apiStatus;
+            var apiStatus = new TwitterApiStatus();
+            MyCommon.TwitterApiInfo = apiStatus;
 
-                var endpoint = new Uri("hoge/tetete.json", UriKind.Relative);
+            var endpoint = new Uri("hoge/tetete.json", UriKind.Relative);
 
-                await apiConnection.GetAsync<string>(endpoint, null, endpointName: "/hoge/tetete")
-                    .ConfigureAwait(false);
+            await apiConnection.GetAsync<string>(endpoint, null, endpointName: "/hoge/tetete")
+                .ConfigureAwait(false);
 
-                Assert.Equal(TwitterApiAccessLevel.ReadWriteAndDirectMessage, apiStatus.AccessLevel);
-                Assert.Equal(new ApiLimit(150, 100, new DateTimeUtc(2013, 1, 1, 0, 0, 0)), apiStatus.AccessLimit["/hoge/tetete"]);
+            Assert.Equal(TwitterApiAccessLevel.ReadWriteAndDirectMessage, apiStatus.AccessLevel);
+            Assert.Equal(new ApiLimit(150, 100, new DateTimeUtc(2013, 1, 1, 0, 0, 0)), apiStatus.AccessLimit["/hoge/tetete"]);
 
-                Assert.Equal(0, mockHandler.QueueCount);
-            }
+            Assert.Equal(0, mockHandler.QueueCount);
         }
 
         [Fact]
         public async Task GetAsync_ErrorStatusTest()
         {
-            using (var mockHandler = new HttpMessageHandlerMock())
-            using (var http = new HttpClient(mockHandler))
-            using (var apiConnection = new TwitterApiConnection("", ""))
-            {
-                apiConnection.http = http;
+            using var mockHandler = new HttpMessageHandlerMock();
+            using var http = new HttpClient(mockHandler);
+            using var apiConnection = new TwitterApiConnection("", "");
+            apiConnection.http = http;
 
-                mockHandler.Enqueue(x =>
+            mockHandler.Enqueue(x =>
+            {
+                return new HttpResponseMessage(HttpStatusCode.BadGateway)
                 {
-                    return new HttpResponseMessage(HttpStatusCode.BadGateway)
-                    {
-                        Content = new StringContent("### Invalid JSON Response ###"),
-                    };
-                });
+                    Content = new StringContent("### Invalid JSON Response ###"),
+                };
+            });
 
-                var endpoint = new Uri("hoge/tetete.json", UriKind.Relative);
+            var endpoint = new Uri("hoge/tetete.json", UriKind.Relative);
 
-                var exception = await Assert.ThrowsAsync<TwitterApiException>(() => apiConnection.GetAsync<string>(endpoint, null, endpointName: "/hoge/tetete"))
-                    .ConfigureAwait(false);
+            var exception = await Assert.ThrowsAsync<TwitterApiException>(() => apiConnection.GetAsync<string>(endpoint, null, endpointName: "/hoge/tetete"))
+                .ConfigureAwait(false);
 
-                // エラーレスポンスの読み込みに失敗した場合はステータスコードをそのままメッセージに使用する
-                Assert.Equal("BadGateway", exception.Message);
-                Assert.Null(exception.ErrorResponse);
+            // エラーレスポンスの読み込みに失敗した場合はステータスコードをそのままメッセージに使用する
+            Assert.Equal("BadGateway", exception.Message);
+            Assert.Null(exception.ErrorResponse);
 
-                Assert.Equal(0, mockHandler.QueueCount);
-            }
+            Assert.Equal(0, mockHandler.QueueCount);
         }
 
         [Fact]
         public async Task GetAsync_ErrorJsonTest()
         {
-            using (var mockHandler = new HttpMessageHandlerMock())
-            using (var http = new HttpClient(mockHandler))
-            using (var apiConnection = new TwitterApiConnection("", ""))
-            {
-                apiConnection.http = http;
+            using var mockHandler = new HttpMessageHandlerMock();
+            using var http = new HttpClient(mockHandler);
+            using var apiConnection = new TwitterApiConnection("", "");
+            apiConnection.http = http;
 
-                mockHandler.Enqueue(x =>
+            mockHandler.Enqueue(x =>
+            {
+                return new HttpResponseMessage(HttpStatusCode.Forbidden)
                 {
-                    return new HttpResponseMessage(HttpStatusCode.Forbidden)
-                    {
-                        Content = new StringContent("{\"errors\":[{\"code\":187,\"message\":\"Status is a duplicate.\"}]}"),
-                    };
-                });
+                    Content = new StringContent("{\"errors\":[{\"code\":187,\"message\":\"Status is a duplicate.\"}]}"),
+                };
+            });
 
-                var endpoint = new Uri("hoge/tetete.json", UriKind.Relative);
+            var endpoint = new Uri("hoge/tetete.json", UriKind.Relative);
 
-                var exception = await Assert.ThrowsAsync<TwitterApiException>(() => apiConnection.GetAsync<string>(endpoint, null, endpointName: "/hoge/tetete"))
-                    .ConfigureAwait(false);
+            var exception = await Assert.ThrowsAsync<TwitterApiException>(() => apiConnection.GetAsync<string>(endpoint, null, endpointName: "/hoge/tetete"))
+                .ConfigureAwait(false);
 
-                // エラーレスポンスの JSON に含まれるエラーコードに基づいてメッセージを出力する
-                Assert.Equal("DuplicateStatus", exception.Message);
+            // エラーレスポンスの JSON に含まれるエラーコードに基づいてメッセージを出力する
+            Assert.Equal("DuplicateStatus", exception.Message);
 
-                Assert.Equal(TwitterErrorCode.DuplicateStatus, exception.ErrorResponse.Errors[0].Code);
-                Assert.Equal("Status is a duplicate.", exception.ErrorResponse.Errors[0].Message);
+            Assert.Equal(TwitterErrorCode.DuplicateStatus, exception.ErrorResponse.Errors[0].Code);
+            Assert.Equal("Status is a duplicate.", exception.ErrorResponse.Errors[0].Message);
 
-                Assert.Equal(0, mockHandler.QueueCount);
-            }
+            Assert.Equal(0, mockHandler.QueueCount);
         }
 
         [Fact]
         public async Task GetStreamAsync_Test()
         {
-            using (var mockHandler = new HttpMessageHandlerMock())
-            using (var http = new HttpClient(mockHandler))
-            using (var apiConnection = new TwitterApiConnection("", ""))
-            using (var image = TestUtils.CreateDummyImage())
-            {
-                apiConnection.http = http;
-
-                mockHandler.Enqueue(x =>
-                {
-                    Assert.Equal(HttpMethod.Get, x.Method);
-                    Assert.Equal("https://api.twitter.com/1.1/hoge/tetete.json",
-                        x.RequestUri.GetLeftPart(UriPartial.Path));
+            using var mockHandler = new HttpMessageHandlerMock();
+            using var http = new HttpClient(mockHandler);
+            using var apiConnection = new TwitterApiConnection("", "");
+            using var image = TestUtils.CreateDummyImage();
+            apiConnection.http = http;
 
-                    var query = HttpUtility.ParseQueryString(x.RequestUri.Query);
+            mockHandler.Enqueue(x =>
+            {
+                Assert.Equal(HttpMethod.Get, x.Method);
+                Assert.Equal("https://api.twitter.com/1.1/hoge/tetete.json",
+                    x.RequestUri.GetLeftPart(UriPartial.Path));
 
-                    Assert.Equal("1111", query["aaaa"]);
-                    Assert.Equal("2222", query["bbbb"]);
+                var query = HttpUtility.ParseQueryString(x.RequestUri.Query);
 
-                    return new HttpResponseMessage(HttpStatusCode.OK)
-                    {
-                        Content = new ByteArrayContent(image.Stream.ToArray()),
-                    };
-                });
+                Assert.Equal("1111", query["aaaa"]);
+                Assert.Equal("2222", query["bbbb"]);
 
-                var endpoint = new Uri("hoge/tetete.json", UriKind.Relative);
-                var param = new Dictionary<string, string>
+                return new HttpResponseMessage(HttpStatusCode.OK)
                 {
-                    ["aaaa"] = "1111",
-                    ["bbbb"] = "2222",
+                    Content = new ByteArrayContent(image.Stream.ToArray()),
                 };
+            });
 
-                var stream = await apiConnection.GetStreamAsync(endpoint, param)
-                    .ConfigureAwait(false);
+            var endpoint = new Uri("hoge/tetete.json", UriKind.Relative);
+            var param = new Dictionary<string, string>
+            {
+                ["aaaa"] = "1111",
+                ["bbbb"] = "2222",
+            };
 
-                using (var memoryStream = new MemoryStream())
-                {
-                    // 内容の比較のために MemoryStream にコピー
-                    await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
+            var stream = await apiConnection.GetStreamAsync(endpoint, param)
+                .ConfigureAwait(false);
 
-                    Assert.Equal(image.Stream.ToArray(), memoryStream.ToArray());
-                }
+            using (var memoryStream = new MemoryStream())
+            {
+                // 内容の比較のために MemoryStream にコピー
+                await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
 
-                Assert.Equal(0, mockHandler.QueueCount);
+                Assert.Equal(image.Stream.ToArray(), memoryStream.ToArray());
             }
+
+            Assert.Equal(0, mockHandler.QueueCount);
         }
 
         [Fact]
         public async Task PostLazyAsync_Test()
         {
-            using (var mockHandler = new HttpMessageHandlerMock())
-            using (var http = new HttpClient(mockHandler))
-            using (var apiConnection = new TwitterApiConnection("", ""))
-            {
-                apiConnection.http = http;
+            using var mockHandler = new HttpMessageHandlerMock();
+            using var http = new HttpClient(mockHandler);
+            using var apiConnection = new TwitterApiConnection("", "");
+            apiConnection.http = http;
 
-                mockHandler.Enqueue(async x =>
-                {
-                    Assert.Equal(HttpMethod.Post, x.Method);
-                    Assert.Equal("https://api.twitter.com/1.1/hoge/tetete.json",
-                        x.RequestUri.AbsoluteUri);
+            mockHandler.Enqueue(async x =>
+            {
+                Assert.Equal(HttpMethod.Post, x.Method);
+                Assert.Equal("https://api.twitter.com/1.1/hoge/tetete.json",
+                    x.RequestUri.AbsoluteUri);
 
-                    var body = await x.Content.ReadAsStringAsync()
-                        .ConfigureAwait(false);
-                    var query = HttpUtility.ParseQueryString(body);
+                var body = await x.Content.ReadAsStringAsync()
+                    .ConfigureAwait(false);
+                var query = HttpUtility.ParseQueryString(body);
 
-                    Assert.Equal("1111", query["aaaa"]);
-                    Assert.Equal("2222", query["bbbb"]);
+                Assert.Equal("1111", query["aaaa"]);
+                Assert.Equal("2222", query["bbbb"]);
 
-                    return new HttpResponseMessage(HttpStatusCode.OK)
-                    {
-                        Content = new StringContent("\"hogehoge\""),
-                    };
-                });
-
-                var endpoint = new Uri("hoge/tetete.json", UriKind.Relative);
-                var param = new Dictionary<string, string>
+                return new HttpResponseMessage(HttpStatusCode.OK)
                 {
-                    ["aaaa"] = "1111",
-                    ["bbbb"] = "2222",
+                    Content = new StringContent("\"hogehoge\""),
                 };
+            });
 
-                var result = await apiConnection.PostLazyAsync<string>(endpoint, param)
-                    .ConfigureAwait(false);
+            var endpoint = new Uri("hoge/tetete.json", UriKind.Relative);
+            var param = new Dictionary<string, string>
+            {
+                ["aaaa"] = "1111",
+                ["bbbb"] = "2222",
+            };
 
-                Assert.Equal("hogehoge", await result.LoadJsonAsync()
-                    .ConfigureAwait(false));
+            var result = await apiConnection.PostLazyAsync<string>(endpoint, param)
+                .ConfigureAwait(false);
 
-                Assert.Equal(0, mockHandler.QueueCount);
-            }
+            Assert.Equal("hogehoge", await result.LoadJsonAsync()
+                .ConfigureAwait(false));
+
+            Assert.Equal(0, mockHandler.QueueCount);
         }
 
         [Fact]
         public async Task PostLazyAsync_MultipartTest()
         {
-            using (var mockHandler = new HttpMessageHandlerMock())
-            using (var http = new HttpClient(mockHandler))
-            using (var apiConnection = new TwitterApiConnection("", ""))
+            using var mockHandler = new HttpMessageHandlerMock();
+            using var http = new HttpClient(mockHandler);
+            using var apiConnection = new TwitterApiConnection("", "");
+            apiConnection.httpUpload = http;
+
+            using var image = TestUtils.CreateDummyImage();
+            using var media = new MemoryImageMediaItem(image);
+
+            mockHandler.Enqueue(async x =>
             {
-                apiConnection.httpUpload = http;
+                Assert.Equal(HttpMethod.Post, x.Method);
+                Assert.Equal("https://api.twitter.com/1.1/hoge/tetete.json",
+                    x.RequestUri.AbsoluteUri);
 
-                using (var image = TestUtils.CreateDummyImage())
-                using (var media = new MemoryImageMediaItem(image))
+                Assert.IsType<MultipartFormDataContent>(x.Content);
+
+                var boundary = x.Content.Headers.ContentType.Parameters.Cast<NameValueHeaderValue>()
+                    .First(y => y.Name == "boundary").Value;
+
+                    // 前後のダブルクオーテーションを除去
+                    boundary = boundary.Substring(1, boundary.Length - 2);
+
+                var expectedText =
+                    $"--{boundary}\r\n" +
+                    "Content-Type: text/plain; charset=utf-8\r\n" +
+                    "Content-Disposition: form-data; name=aaaa\r\n" +
+                    "\r\n" +
+                    "1111\r\n" +
+                    $"--{boundary}\r\n" +
+                    "Content-Type: text/plain; charset=utf-8\r\n" +
+                    "Content-Disposition: form-data; name=bbbb\r\n" +
+                    "\r\n" +
+                    "2222\r\n" +
+                    $"--{boundary}\r\n" +
+                    $"Content-Disposition: form-data; name=media1; filename={media.Name}; filename*=utf-8''{media.Name}\r\n" +
+                    "\r\n";
+
+                var expected = Encoding.UTF8.GetBytes(expectedText)
+                    .Concat(image.Stream.ToArray())
+                    .Concat(Encoding.UTF8.GetBytes($"\r\n--{boundary}--\r\n"));
+
+                Assert.Equal(expected, await x.Content.ReadAsByteArrayAsync().ConfigureAwait(false));
+
+                return new HttpResponseMessage(HttpStatusCode.OK)
                 {
-                    mockHandler.Enqueue(async x =>
-                    {
-                        Assert.Equal(HttpMethod.Post, x.Method);
-                        Assert.Equal("https://api.twitter.com/1.1/hoge/tetete.json",
-                            x.RequestUri.AbsoluteUri);
-
-                        Assert.IsType<MultipartFormDataContent>(x.Content);
-
-                        var boundary = x.Content.Headers.ContentType.Parameters.Cast<NameValueHeaderValue>()
-                            .First(y => y.Name == "boundary").Value;
-
-                        // 前後のダブルクオーテーションを除去
-                        boundary = boundary.Substring(1, boundary.Length - 2);
-
-                        var expectedText =
-                            $"--{boundary}\r\n" +
-                            "Content-Type: text/plain; charset=utf-8\r\n" +
-                            "Content-Disposition: form-data; name=aaaa\r\n" +
-                            "\r\n" +
-                            "1111\r\n"+
-                            $"--{boundary}\r\n" +
-                            "Content-Type: text/plain; charset=utf-8\r\n" +
-                            "Content-Disposition: form-data; name=bbbb\r\n" +
-                            "\r\n" +
-                            "2222\r\n" +
-                            $"--{boundary}\r\n" +
-                            $"Content-Disposition: form-data; name=media1; filename={media.Name}; filename*=utf-8''{media.Name}\r\n" +
-                            "\r\n";
-
-                        var expected = Encoding.UTF8.GetBytes(expectedText)
-                            .Concat(image.Stream.ToArray())
-                            .Concat(Encoding.UTF8.GetBytes($"\r\n--{boundary}--\r\n"));
-
-                        Assert.Equal(expected, await x.Content.ReadAsByteArrayAsync().ConfigureAwait(false));
-
-                        return new HttpResponseMessage(HttpStatusCode.OK)
-                        {
-                            Content = new StringContent("\"hogehoge\""),
-                        };
-                    });
-
-                    var endpoint = new Uri("hoge/tetete.json", UriKind.Relative);
-                    var param = new Dictionary<string, string>
-                    {
-                        ["aaaa"] = "1111",
-                        ["bbbb"] = "2222",
-                    };
-                    var mediaParam = new Dictionary<string, IMediaItem>
-                    {
-                        ["media1"] = media,
-                    };
+                    Content = new StringContent("\"hogehoge\""),
+                };
+            });
 
-                    var result = await apiConnection.PostLazyAsync<string>(endpoint, param, mediaParam)
-                        .ConfigureAwait(false);
+            var endpoint = new Uri("hoge/tetete.json", UriKind.Relative);
+            var param = new Dictionary<string, string>
+            {
+                ["aaaa"] = "1111",
+                ["bbbb"] = "2222",
+            };
+            var mediaParam = new Dictionary<string, IMediaItem>
+            {
+                ["media1"] = media,
+            };
 
-                    Assert.Equal("hogehoge", await result.LoadJsonAsync()
-                        .ConfigureAwait(false));
+            var result = await apiConnection.PostLazyAsync<string>(endpoint, param, mediaParam)
+                .ConfigureAwait(false);
 
-                    Assert.Equal(0, mockHandler.QueueCount);
-                }
-            }
+            Assert.Equal("hogehoge", await result.LoadJsonAsync()
+                .ConfigureAwait(false));
+
+            Assert.Equal(0, mockHandler.QueueCount);
         }
 
         [Fact]
         public async Task PostLazyAsync_Multipart_NullTest()
         {
-            using (var mockHandler = new HttpMessageHandlerMock())
-            using (var http = new HttpClient(mockHandler))
-            using (var apiConnection = new TwitterApiConnection("", ""))
-            {
-                apiConnection.httpUpload = http;
+            using var mockHandler = new HttpMessageHandlerMock();
+            using var http = new HttpClient(mockHandler);
+            using var apiConnection = new TwitterApiConnection("", "");
+            apiConnection.httpUpload = http;
 
-                mockHandler.Enqueue(async x =>
-                {
-                    Assert.Equal(HttpMethod.Post, x.Method);
-                    Assert.Equal("https://api.twitter.com/1.1/hoge/tetete.json",
-                        x.RequestUri.AbsoluteUri);
+            mockHandler.Enqueue(async x =>
+            {
+                Assert.Equal(HttpMethod.Post, x.Method);
+                Assert.Equal("https://api.twitter.com/1.1/hoge/tetete.json",
+                    x.RequestUri.AbsoluteUri);
 
-                    Assert.IsType<MultipartFormDataContent>(x.Content);
+                Assert.IsType<MultipartFormDataContent>(x.Content);
 
-                    var boundary = x.Content.Headers.ContentType.Parameters.Cast<NameValueHeaderValue>()
-                        .First(y => y.Name == "boundary").Value;
+                var boundary = x.Content.Headers.ContentType.Parameters.Cast<NameValueHeaderValue>()
+                    .First(y => y.Name == "boundary").Value;
 
                     // 前後のダブルクオーテーションを除去
                     boundary = boundary.Substring(1, boundary.Length - 2);
 
-                    var expectedText =
-                        $"--{boundary}\r\n" +
-                        $"\r\n--{boundary}--\r\n";
+                var expectedText =
+                    $"--{boundary}\r\n" +
+                    $"\r\n--{boundary}--\r\n";
 
-                    var expected = Encoding.UTF8.GetBytes(expectedText);
+                var expected = Encoding.UTF8.GetBytes(expectedText);
 
-                    Assert.Equal(expected, await x.Content.ReadAsByteArrayAsync().ConfigureAwait(false));
+                Assert.Equal(expected, await x.Content.ReadAsByteArrayAsync().ConfigureAwait(false));
 
-                    return new HttpResponseMessage(HttpStatusCode.OK)
-                    {
-                        Content = new StringContent("\"hogehoge\""),
-                    };
-                });
+                return new HttpResponseMessage(HttpStatusCode.OK)
+                {
+                    Content = new StringContent("\"hogehoge\""),
+                };
+            });
 
-                var endpoint = new Uri("hoge/tetete.json", UriKind.Relative);
+            var endpoint = new Uri("hoge/tetete.json", UriKind.Relative);
 
-                var result = await apiConnection.PostLazyAsync<string>(endpoint, param: null, media: null)
-                    .ConfigureAwait(false);
+            var result = await apiConnection.PostLazyAsync<string>(endpoint, param: null, media: null)
+                .ConfigureAwait(false);
 
-                Assert.Equal("hogehoge", await result.LoadJsonAsync()
-                    .ConfigureAwait(false));
+            Assert.Equal("hogehoge", await result.LoadJsonAsync()
+                .ConfigureAwait(false));
 
-                Assert.Equal(0, mockHandler.QueueCount);
-            }
+            Assert.Equal(0, mockHandler.QueueCount);
         }
 
         [Fact]
         public async Task PostJsonAsync_Test()
         {
-            using (var mockHandler = new HttpMessageHandlerMock())
-            using (var http = new HttpClient(mockHandler))
-            using (var apiConnection = new TwitterApiConnection("", ""))
-            {
-                apiConnection.http = http;
+            using var mockHandler = new HttpMessageHandlerMock();
+            using var http = new HttpClient(mockHandler);
+            using var apiConnection = new TwitterApiConnection("", "");
+            apiConnection.http = http;
 
-                mockHandler.Enqueue(async x =>
-                {
-                    Assert.Equal(HttpMethod.Post, x.Method);
-                    Assert.Equal("https://api.twitter.com/1.1/hoge/tetete.json",
-                        x.RequestUri.AbsoluteUri);
+            mockHandler.Enqueue(async x =>
+            {
+                Assert.Equal(HttpMethod.Post, x.Method);
+                Assert.Equal("https://api.twitter.com/1.1/hoge/tetete.json",
+                    x.RequestUri.AbsoluteUri);
 
-                    Assert.Equal("application/json; charset=utf-8", x.Content.Headers.ContentType.ToString());
+                Assert.Equal("application/json; charset=utf-8", x.Content.Headers.ContentType.ToString());
 
-                    var body = await x.Content.ReadAsStringAsync()
-                        .ConfigureAwait(false);
+                var body = await x.Content.ReadAsStringAsync()
+                    .ConfigureAwait(false);
 
-                    Assert.Equal("{\"aaaa\": 1111}", body);
+                Assert.Equal("{\"aaaa\": 1111}", body);
 
-                    return new HttpResponseMessage(HttpStatusCode.NoContent);
-                });
+                return new HttpResponseMessage(HttpStatusCode.NoContent);
+            });
 
-                var endpoint = new Uri("hoge/tetete.json", UriKind.Relative);
+            var endpoint = new Uri("hoge/tetete.json", UriKind.Relative);
 
-                await apiConnection.PostJsonAsync(endpoint, "{\"aaaa\": 1111}")
-                    .ConfigureAwait(false);
+            await apiConnection.PostJsonAsync(endpoint, "{\"aaaa\": 1111}")
+                .ConfigureAwait(false);
 
-                Assert.Equal(0, mockHandler.QueueCount);
-            }
+            Assert.Equal(0, mockHandler.QueueCount);
         }
 
         [Fact]
         public async Task PostJsonAsync_T_Test()
         {
-            using (var mockHandler = new HttpMessageHandlerMock())
-            using (var http = new HttpClient(mockHandler))
-            using (var apiConnection = new TwitterApiConnection("", ""))
-            {
-                apiConnection.http = http;
+            using var mockHandler = new HttpMessageHandlerMock();
+            using var http = new HttpClient(mockHandler);
+            using var apiConnection = new TwitterApiConnection("", "");
+            apiConnection.http = http;
 
-                mockHandler.Enqueue(async x =>
-                {
-                    Assert.Equal(HttpMethod.Post, x.Method);
-                    Assert.Equal("https://api.twitter.com/1.1/hoge/tetete.json",
-                        x.RequestUri.AbsoluteUri);
+            mockHandler.Enqueue(async x =>
+            {
+                Assert.Equal(HttpMethod.Post, x.Method);
+                Assert.Equal("https://api.twitter.com/1.1/hoge/tetete.json",
+                    x.RequestUri.AbsoluteUri);
 
-                    Assert.Equal("application/json; charset=utf-8", x.Content.Headers.ContentType.ToString());
+                Assert.Equal("application/json; charset=utf-8", x.Content.Headers.ContentType.ToString());
 
-                    var body = await x.Content.ReadAsStringAsync()
-                        .ConfigureAwait(false);
+                var body = await x.Content.ReadAsStringAsync()
+                    .ConfigureAwait(false);
 
-                    Assert.Equal("{\"aaaa\": 1111}", body);
+                Assert.Equal("{\"aaaa\": 1111}", body);
 
-                    return new HttpResponseMessage(HttpStatusCode.OK)
-                    {
-                        Content = new StringContent("\"hogehoge\""),
-                    };
-                });
+                return new HttpResponseMessage(HttpStatusCode.OK)
+                {
+                    Content = new StringContent("\"hogehoge\""),
+                };
+            });
 
-                var endpoint = new Uri("hoge/tetete.json", UriKind.Relative);
+            var endpoint = new Uri("hoge/tetete.json", UriKind.Relative);
 
-                var response = await apiConnection.PostJsonAsync<string>(endpoint, "{\"aaaa\": 1111}")
-                    .ConfigureAwait(false);
+            var response = await apiConnection.PostJsonAsync<string>(endpoint, "{\"aaaa\": 1111}")
+                .ConfigureAwait(false);
 
-                var result = await response.LoadJsonAsync()
-                    .ConfigureAwait(false);
+            var result = await response.LoadJsonAsync()
+                .ConfigureAwait(false);
 
-                Assert.Equal("hogehoge", result);
+            Assert.Equal("hogehoge", result);
 
-                Assert.Equal(0, mockHandler.QueueCount);
-            }
+            Assert.Equal(0, mockHandler.QueueCount);
         }
 
         [Fact]
         public async Task DeleteAsync_Test()
         {
-            using (var mockHandler = new HttpMessageHandlerMock())
-            using (var http = new HttpClient(mockHandler))
-            using (var apiConnection = new TwitterApiConnection("", ""))
-            {
-                apiConnection.http = http;
+            using var mockHandler = new HttpMessageHandlerMock();
+            using var http = new HttpClient(mockHandler);
+            using var apiConnection = new TwitterApiConnection("", "");
+            apiConnection.http = http;
 
-                mockHandler.Enqueue(x =>
-                {
-                    Assert.Equal(HttpMethod.Delete, x.Method);
-                    Assert.Equal("https://api.twitter.com/1.1/hoge/tetete.json",
-                        x.RequestUri.AbsoluteUri);
+            mockHandler.Enqueue(x =>
+            {
+                Assert.Equal(HttpMethod.Delete, x.Method);
+                Assert.Equal("https://api.twitter.com/1.1/hoge/tetete.json",
+                    x.RequestUri.AbsoluteUri);
 
-                    return new HttpResponseMessage(HttpStatusCode.NoContent);
-                });
+                return new HttpResponseMessage(HttpStatusCode.NoContent);
+            });
 
-                var endpoint = new Uri("hoge/tetete.json", UriKind.Relative);
+            var endpoint = new Uri("hoge/tetete.json", UriKind.Relative);
 
-                await apiConnection.DeleteAsync(endpoint)
-                    .ConfigureAwait(false);
+            await apiConnection.DeleteAsync(endpoint)
+                .ConfigureAwait(false);
 
-                Assert.Equal(0, mockHandler.QueueCount);
-            }
+            Assert.Equal(0, mockHandler.QueueCount);
         }
     }
 }
index 93df7b4..384c286 100644 (file)
@@ -38,14 +38,12 @@ namespace OpenTween
         {
             var hashtags = new[] { "#foo", "#bar" };
 
-            using (var atDialog = new AtIdSupplement())
-            using (var hashDialog = new HashtagManage(atDialog, hashtags, "", false, false, false))
-            {
-                hashDialog.RunSilent = true;
-
-                Assert.Equal(new[] { "#foo", "#bar" }, hashDialog.HistoryHashList.Items.Cast<string>());
-                Assert.Equal(new[] { "#foo", "#bar" }, hashDialog.HashHistories);
-            }
+            using var atDialog = new AtIdSupplement();
+            using var hashDialog = new HashtagManage(atDialog, hashtags, "", false, false, false);
+            hashDialog.RunSilent = true;
+
+            Assert.Equal(new[] { "#foo", "#bar" }, hashDialog.HistoryHashList.Items.Cast<string>());
+            Assert.Equal(new[] { "#foo", "#bar" }, hashDialog.HashHistories);
         }
 
         [Fact]
@@ -53,52 +51,46 @@ namespace OpenTween
         {
             var hashtags = Array.Empty<string>();
 
-            using (var atDialog = new AtIdSupplement())
-            using (var hashDialog = new HashtagManage(atDialog, hashtags, "", false, false, false))
-            {
-                hashDialog.RunSilent = true;
+            using var atDialog = new AtIdSupplement();
+            using var hashDialog = new HashtagManage(atDialog, hashtags, "", false, false, false);
+            hashDialog.RunSilent = true;
 
-                Assert.Empty(hashDialog.HistoryHashList.Items);
-                Assert.Empty(hashDialog.HashHistories);
-            }
+            Assert.Empty(hashDialog.HistoryHashList.Items);
+            Assert.Empty(hashDialog.HashHistories);
         }
 
         [Fact]
         public void AddHashtag_Test()
         {
-            using (var atDialog = new AtIdSupplement())
-            using (var hashDialog = new HashtagManage(atDialog, Array.Empty<string>(), "", false, false, false))
-            {
-                hashDialog.RunSilent = true;
+            using var atDialog = new AtIdSupplement();
+            using var hashDialog = new HashtagManage(atDialog, Array.Empty<string>(), "", false, false, false);
+            hashDialog.RunSilent = true;
 
-                TestUtils.FireEvent(hashDialog.AddButton, "Click"); // 「新規 (&N)」ボタン
+            TestUtils.FireEvent(hashDialog.AddButton, "Click"); // 「新規 (&N)」ボタン
 
-                hashDialog.UseHashText.Text = "#OpenTween";
+            hashDialog.UseHashText.Text = "#OpenTween";
 
-                TestUtils.FireEvent(hashDialog.PermOK_Button, "Click"); // 「詳細」グループ内の「OK」ボタン
+            TestUtils.FireEvent(hashDialog.PermOK_Button, "Click"); // 「詳細」グループ内の「OK」ボタン
 
-                Assert.Equal(new[] { "#OpenTween" }, hashDialog.HistoryHashList.Items.Cast<string>());
-                Assert.Equal(new[] { "#OpenTween" }, hashDialog.HashHistories);
-            }
+            Assert.Equal(new[] { "#OpenTween" }, hashDialog.HistoryHashList.Items.Cast<string>());
+            Assert.Equal(new[] { "#OpenTween" }, hashDialog.HashHistories);
         }
 
         [Fact]
         public void AddHashtag_FullWidthTest()
         {
-            using (var atDialog = new AtIdSupplement())
-            using (var hashDialog = new HashtagManage(atDialog, Array.Empty<string>(), "", false, false, false))
-            {
-                hashDialog.RunSilent = true;
+            using var atDialog = new AtIdSupplement();
+            using var hashDialog = new HashtagManage(atDialog, Array.Empty<string>(), "", false, false, false);
+            hashDialog.RunSilent = true;
 
-                TestUtils.FireEvent(hashDialog.AddButton, "Click"); // 「新規 (&N)」ボタン
+            TestUtils.FireEvent(hashDialog.AddButton, "Click"); // 「新規 (&N)」ボタン
 
-                hashDialog.UseHashText.Text = "#ほげほげ";
+            hashDialog.UseHashText.Text = "#ほげほげ";
 
-                TestUtils.FireEvent(hashDialog.PermOK_Button, "Click"); // 「詳細」グループ内の「OK」ボタン
+            TestUtils.FireEvent(hashDialog.PermOK_Button, "Click"); // 「詳細」グループ内の「OK」ボタン
 
-                Assert.Equal(new[] { "#ほげほげ" }, hashDialog.HistoryHashList.Items.Cast<string>());
-                Assert.Equal(new[] { "#ほげほげ" }, hashDialog.HashHistories);
-            }
+            Assert.Equal(new[] { "#ほげほげ" }, hashDialog.HistoryHashList.Items.Cast<string>());
+            Assert.Equal(new[] { "#ほげほげ" }, hashDialog.HashHistories);
         }
 
         [Fact]
@@ -106,60 +98,54 @@ namespace OpenTween
         {
             // ハッシュタグを表す「#」の直後に結合文字 (濁点など) が続いた場合に対するテスト
 
-            using (var atDialog = new AtIdSupplement())
-            using (var hashDialog = new HashtagManage(atDialog, Array.Empty<string>(), "", false, false, false))
-            {
-                hashDialog.RunSilent = true;
+            using var atDialog = new AtIdSupplement();
+            using var hashDialog = new HashtagManage(atDialog, Array.Empty<string>(), "", false, false, false);
+            hashDialog.RunSilent = true;
 
-                TestUtils.FireEvent(hashDialog.AddButton, "Click"); // 「新規 (&N)」ボタン
+            TestUtils.FireEvent(hashDialog.AddButton, "Click"); // 「新規 (&N)」ボタン
 
-                // どんちき└(^ω^ )┐♫ ┌( ^ω^)┘♫どんちき
-                hashDialog.UseHashText.Text = "#゛t゛e゛s゛a゛b゛u゛";
+            // どんちき└(^ω^ )┐♫ ┌( ^ω^)┘♫どんちき
+            hashDialog.UseHashText.Text = "#゛t゛e゛s゛a゛b゛u゛";
 
-                TestUtils.FireEvent(hashDialog.PermOK_Button, "Click"); // 「詳細」グループ内の「OK」ボタン
+            TestUtils.FireEvent(hashDialog.PermOK_Button, "Click"); // 「詳細」グループ内の「OK」ボタン
 
-                Assert.Equal(new[] { "#゛t゛e゛s゛a゛b゛u゛" }, hashDialog.HistoryHashList.Items.Cast<string>());
-                Assert.Equal(new[] { "#゛t゛e゛s゛a゛b゛u゛" }, hashDialog.HashHistories);
-            }
+            Assert.Equal(new[] { "#゛t゛e゛s゛a゛b゛u゛" }, hashDialog.HistoryHashList.Items.Cast<string>());
+            Assert.Equal(new[] { "#゛t゛e゛s゛a゛b゛u゛" }, hashDialog.HashHistories);
         }
 
         [Fact]
         public void AddHashtag_MultipleTest()
         {
-            using (var atDialog = new AtIdSupplement())
-            using (var hashDialog = new HashtagManage(atDialog, Array.Empty<string>(), "", false, false, false))
-            {
-                hashDialog.RunSilent = true;
+            using var atDialog = new AtIdSupplement();
+            using var hashDialog = new HashtagManage(atDialog, Array.Empty<string>(), "", false, false, false);
+            hashDialog.RunSilent = true;
 
-                TestUtils.FireEvent(hashDialog.AddButton, "Click"); // 「新規 (&N)」ボタン
+            TestUtils.FireEvent(hashDialog.AddButton, "Click"); // 「新規 (&N)」ボタン
 
-                hashDialog.UseHashText.Text = "#foo #bar";
+            hashDialog.UseHashText.Text = "#foo #bar";
 
-                TestUtils.FireEvent(hashDialog.PermOK_Button, "Click"); // 「詳細」グループ内の「OK」ボタン
+            TestUtils.FireEvent(hashDialog.PermOK_Button, "Click"); // 「詳細」グループ内の「OK」ボタン
 
-                Assert.Equal(new[] { "#foo #bar" }, hashDialog.HistoryHashList.Items.Cast<string>());
-                Assert.Equal(new[] { "#foo #bar" }, hashDialog.HashHistories);
-            }
+            Assert.Equal(new[] { "#foo #bar" }, hashDialog.HistoryHashList.Items.Cast<string>());
+            Assert.Equal(new[] { "#foo #bar" }, hashDialog.HashHistories);
         }
 
         [Fact]
         public void AddHashtag_InvalidTest()
         {
-            using (var atDialog = new AtIdSupplement())
-            using (var hashDialog = new HashtagManage(atDialog, Array.Empty<string>(), "", false, false, false))
-            {
-                hashDialog.RunSilent = true;
+            using var atDialog = new AtIdSupplement();
+            using var hashDialog = new HashtagManage(atDialog, Array.Empty<string>(), "", false, false, false);
+            hashDialog.RunSilent = true;
 
-                TestUtils.FireEvent(hashDialog.AddButton, "Click"); // 「新規 (&N)」ボタン
+            TestUtils.FireEvent(hashDialog.AddButton, "Click"); // 「新規 (&N)」ボタン
 
-                hashDialog.UseHashText.Text = "hogehoge";
+            hashDialog.UseHashText.Text = "hogehoge";
 
-                TestUtils.FireEvent(hashDialog.PermOK_Button, "Click"); // 「詳細」グループ内の「OK」ボタン
-                // 実際にはここでエラーメッセージが出る
+            TestUtils.FireEvent(hashDialog.PermOK_Button, "Click"); // 「詳細」グループ内の「OK」ボタン
+                                                                    // 実際にはここでエラーメッセージが出る
 
-                Assert.Empty(hashDialog.HistoryHashList.Items);
-                Assert.Empty(hashDialog.HashHistories);
-            }
+            Assert.Empty(hashDialog.HistoryHashList.Items);
+            Assert.Empty(hashDialog.HashHistories);
         }
 
         [Fact]
@@ -167,22 +153,20 @@ namespace OpenTween
         {
             var hashtags = new[] { "#foo", "#bar" };
 
-            using (var atDialog = new AtIdSupplement())
-            using (var hashDialog = new HashtagManage(atDialog, hashtags, "", false, false, false))
-            {
-                hashDialog.RunSilent = true;
+            using var atDialog = new AtIdSupplement();
+            using var hashDialog = new HashtagManage(atDialog, hashtags, "", false, false, false);
+            hashDialog.RunSilent = true;
 
-                hashDialog.HistoryHashList.SelectedIndices.Add(0);
+            hashDialog.HistoryHashList.SelectedIndices.Add(0);
 
-                TestUtils.FireEvent(hashDialog.EditButton, "Click"); // 「編集(&E)」ボタン
+            TestUtils.FireEvent(hashDialog.EditButton, "Click"); // 「編集(&E)」ボタン
 
-                hashDialog.UseHashText.Text = "#hoge";
+            hashDialog.UseHashText.Text = "#hoge";
 
-                TestUtils.FireEvent(hashDialog.PermOK_Button, "Click"); // 「詳細」グループ内の「OK」ボタン
+            TestUtils.FireEvent(hashDialog.PermOK_Button, "Click"); // 「詳細」グループ内の「OK」ボタン
 
-                Assert.Equal(new[] { "#hoge", "#bar" }, hashDialog.HistoryHashList.Items.Cast<string>());
-                Assert.Equal(new[] { "#hoge", "#bar" }, hashDialog.HashHistories);
-            }
+            Assert.Equal(new[] { "#hoge", "#bar" }, hashDialog.HistoryHashList.Items.Cast<string>());
+            Assert.Equal(new[] { "#hoge", "#bar" }, hashDialog.HashHistories);
         }
 
         [Fact]
@@ -190,18 +174,16 @@ namespace OpenTween
         {
             var hashtags = new[] { "#foo", "#bar" };
 
-            using (var atDialog = new AtIdSupplement())
-            using (var hashDialog = new HashtagManage(atDialog, hashtags, "", false, false, false))
-            {
-                hashDialog.RunSilent = true;
+            using var atDialog = new AtIdSupplement();
+            using var hashDialog = new HashtagManage(atDialog, hashtags, "", false, false, false);
+            hashDialog.RunSilent = true;
 
-                hashDialog.HistoryHashList.SelectedIndices.Add(1);
+            hashDialog.HistoryHashList.SelectedIndices.Add(1);
 
-                TestUtils.FireEvent(hashDialog.DeleteButton, "Click"); // 「削除(&D)」ボタン
+            TestUtils.FireEvent(hashDialog.DeleteButton, "Click"); // 「削除(&D)」ボタン
 
-                Assert.Equal(new[] { "#foo" }, hashDialog.HistoryHashList.Items.Cast<string>());
-                Assert.Equal(new[] { "#foo" }, hashDialog.HashHistories);
-            }
+            Assert.Equal(new[] { "#foo" }, hashDialog.HistoryHashList.Items.Cast<string>());
+            Assert.Equal(new[] { "#foo" }, hashDialog.HashHistories);
         }
 
         [Fact]
@@ -209,19 +191,17 @@ namespace OpenTween
         {
             var hashtags = new[] { "#foo", "#bar", "#baz" };
 
-            using (var atDialog = new AtIdSupplement())
-            using (var hashDialog = new HashtagManage(atDialog, hashtags, "", false, false, false))
-            {
-                hashDialog.RunSilent = true;
+            using var atDialog = new AtIdSupplement();
+            using var hashDialog = new HashtagManage(atDialog, hashtags, "", false, false, false);
+            hashDialog.RunSilent = true;
 
-                hashDialog.HistoryHashList.SelectedIndices.Add(2);
-                hashDialog.HistoryHashList.SelectedIndices.Add(1);
+            hashDialog.HistoryHashList.SelectedIndices.Add(2);
+            hashDialog.HistoryHashList.SelectedIndices.Add(1);
 
-                TestUtils.FireEvent(hashDialog.DeleteButton, "Click"); // 「削除(&D)」ボタン
+            TestUtils.FireEvent(hashDialog.DeleteButton, "Click"); // 「削除(&D)」ボタン
 
-                Assert.Equal(new[] { "#foo" }, hashDialog.HistoryHashList.Items.Cast<string>());
-                Assert.Equal(new[] { "#foo" }, hashDialog.HashHistories);
-            }
+            Assert.Equal(new[] { "#foo" }, hashDialog.HistoryHashList.Items.Cast<string>());
+            Assert.Equal(new[] { "#foo" }, hashDialog.HashHistories);
         }
 
         [Fact]
@@ -229,18 +209,16 @@ namespace OpenTween
         {
             var hashtags = new[] { "#foo", "#bar" };
 
-            using (var atDialog = new AtIdSupplement())
-            using (var hashDialog = new HashtagManage(atDialog, hashtags, "", false, false, false))
-            {
-                hashDialog.RunSilent = true;
+            using var atDialog = new AtIdSupplement();
+            using var hashDialog = new HashtagManage(atDialog, hashtags, "", false, false, false);
+            hashDialog.RunSilent = true;
 
-                // ハッシュタグを選択していない状態
+            // ハッシュタグを選択していない状態
 
-                TestUtils.FireEvent(hashDialog.DeleteButton, "Click"); // 「削除(&D)」ボタン
+            TestUtils.FireEvent(hashDialog.DeleteButton, "Click"); // 「削除(&D)」ボタン
 
-                Assert.Equal(new[] { "#foo", "#bar" }, hashDialog.HistoryHashList.Items.Cast<string>());
-                Assert.Equal(new[] { "#foo", "#bar" }, hashDialog.HashHistories);
-            }
+            Assert.Equal(new[] { "#foo", "#bar" }, hashDialog.HistoryHashList.Items.Cast<string>());
+            Assert.Equal(new[] { "#foo", "#bar" }, hashDialog.HashHistories);
         }
 
         [Fact]
@@ -248,47 +226,43 @@ namespace OpenTween
         {
             var hashtags = new[] { "#foo" };
 
-            using (var atDialog = new AtIdSupplement())
-            using (var hashDialog = new HashtagManage(atDialog, hashtags, "", false, false, false))
-            {
-                hashDialog.RunSilent = true;
+            using var atDialog = new AtIdSupplement();
+            using var hashDialog = new HashtagManage(atDialog, hashtags, "", false, false, false);
+            hashDialog.RunSilent = true;
 
-                hashDialog.HistoryHashList.SelectedIndices.Add(0);
+            hashDialog.HistoryHashList.SelectedIndices.Add(0);
 
-                TestUtils.FireEvent(hashDialog.UnSelectButton, "Click"); // 「非使用(&U)」ボタン
+            TestUtils.FireEvent(hashDialog.UnSelectButton, "Click"); // 「非使用(&U)」ボタン
 
-                Assert.Empty(hashDialog.HistoryHashList.SelectedIndices);
-            }
+            Assert.Empty(hashDialog.HistoryHashList.SelectedIndices);
         }
 
         [Fact]
         public void EditModeSwitch_Test()
         {
-            using (var atDialog = new AtIdSupplement())
-            using (var hashDialog = new HashtagManage(atDialog, Array.Empty<string>(), "", false, false, false))
-            {
-                hashDialog.RunSilent = true;
+            using var atDialog = new AtIdSupplement();
+            using var hashDialog = new HashtagManage(atDialog, Array.Empty<string>(), "", false, false, false);
+            hashDialog.RunSilent = true;
 
-                Assert.True(hashDialog.GroupHashtag.Enabled);
-                Assert.True(hashDialog.TableLayoutButtons.Enabled);
-                Assert.False(hashDialog.GroupDetail.Enabled);
+            Assert.True(hashDialog.GroupHashtag.Enabled);
+            Assert.True(hashDialog.TableLayoutButtons.Enabled);
+            Assert.False(hashDialog.GroupDetail.Enabled);
 
-                TestUtils.FireEvent(hashDialog.AddButton, "Click"); // 「新規 (&N)」ボタン
+            TestUtils.FireEvent(hashDialog.AddButton, "Click"); // 「新規 (&N)」ボタン
 
-                // 編集モードに入る
-                Assert.False(hashDialog.GroupHashtag.Enabled);
-                Assert.False(hashDialog.TableLayoutButtons.Enabled);
-                Assert.True(hashDialog.GroupDetail.Enabled);
+            // 編集モードに入る
+            Assert.False(hashDialog.GroupHashtag.Enabled);
+            Assert.False(hashDialog.TableLayoutButtons.Enabled);
+            Assert.True(hashDialog.GroupDetail.Enabled);
 
-                hashDialog.UseHashText.Text = "#hogehoge";
+            hashDialog.UseHashText.Text = "#hogehoge";
 
-                TestUtils.FireEvent(hashDialog.PermOK_Button, "Click"); // 「詳細」グループ内の「OK」ボタン
+            TestUtils.FireEvent(hashDialog.PermOK_Button, "Click"); // 「詳細」グループ内の「OK」ボタン
 
-                // 編集モードから抜ける
-                Assert.True(hashDialog.GroupHashtag.Enabled);
-                Assert.True(hashDialog.TableLayoutButtons.Enabled);
-                Assert.False(hashDialog.GroupDetail.Enabled);
-            }
+            // 編集モードから抜ける
+            Assert.True(hashDialog.GroupHashtag.Enabled);
+            Assert.True(hashDialog.TableLayoutButtons.Enabled);
+            Assert.False(hashDialog.GroupDetail.Enabled);
         }
     }
 }
index 91b9361..a4da436 100644 (file)
@@ -30,454 +30,422 @@ namespace OpenTween
         [Fact]
         public void Initialize_TwitterTest()
         {
-            using (var twitter = new Twitter())
-            using (var mediaSelector = new MediaSelector())
-            {
-                twitter.Initialize("", "", "", 0L);
-                mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");
+            using var twitter = new Twitter();
+            using var mediaSelector = new MediaSelector();
+            twitter.Initialize("", "", "", 0L);
+            mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");
 
-                Assert.NotEqual(-1, mediaSelector.ImageServiceCombo.Items.IndexOf("Twitter"));
+            Assert.NotEqual(-1, mediaSelector.ImageServiceCombo.Items.IndexOf("Twitter"));
 
-                // 投稿先に Twitter が選択されている
-                Assert.Equal("Twitter", mediaSelector.ImageServiceCombo.Text);
+            // 投稿先に Twitter が選択されている
+            Assert.Equal("Twitter", mediaSelector.ImageServiceCombo.Text);
 
-                // ページ番号が初期化された状態
-                var pages = mediaSelector.ImagePageCombo.Items;
-                Assert.Equal(new[] { "1" }, pages.Cast<object>().Select(x => x.ToString()));
+            // ページ番号が初期化された状態
+            var pages = mediaSelector.ImagePageCombo.Items;
+            Assert.Equal(new[] { "1" }, pages.Cast<object>().Select(x => x.ToString()));
 
-                // 代替テキストの入力欄が表示された状態
-                Assert.True(mediaSelector.AlternativeTextPanel.Visible);
-            }
+            // 代替テキストの入力欄が表示された状態
+            Assert.True(mediaSelector.AlternativeTextPanel.Visible);
         }
 
         [Fact]
         public void Initialize_ImgurTest()
         {
-            using (var twitter = new Twitter())
-            using (var mediaSelector = new MediaSelector())
-            {
-                twitter.Initialize("", "", "", 0L);
-                mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Imgur");
+            using var twitter = new Twitter();
+            using var mediaSelector = new MediaSelector();
+            twitter.Initialize("", "", "", 0L);
+            mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Imgur");
 
-                // 投稿先に Imgur が選択されている
-                Assert.Equal("Imgur", mediaSelector.ImageServiceCombo.Text);
+            // 投稿先に Imgur が選択されている
+            Assert.Equal("Imgur", mediaSelector.ImageServiceCombo.Text);
 
-                // ページ番号が初期化された状態
-                var pages = mediaSelector.ImagePageCombo.Items;
-                Assert.Equal(new[] { "1" }, pages.Cast<object>().Select(x => x.ToString()));
+            // ページ番号が初期化された状態
+            var pages = mediaSelector.ImagePageCombo.Items;
+            Assert.Equal(new[] { "1" }, pages.Cast<object>().Select(x => x.ToString()));
 
-                // 代替テキストの入力欄が非表示の状態
-                Assert.False(mediaSelector.AlternativeTextPanel.Visible);
-            }
+            // 代替テキストの入力欄が非表示の状態
+            Assert.False(mediaSelector.AlternativeTextPanel.Visible);
         }
 
         [Fact]
         public void BeginSelection_BlankTest()
         {
-            using (var twitter = new Twitter())
-            using (var mediaSelector = new MediaSelector { Visible = false, Enabled = false })
-            {
-                twitter.Initialize("", "", "", 0L);
-                mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");
+            using var twitter = new Twitter();
+            using var mediaSelector = new MediaSelector { Visible = false, Enabled = false };
+            twitter.Initialize("", "", "", 0L);
+            mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");
+
+            Assert.Raises<EventArgs>(
+                x => mediaSelector.BeginSelecting += x,
+                x => mediaSelector.BeginSelecting -= x,
+                () => mediaSelector.BeginSelection()
+            );
+
+            Assert.True(mediaSelector.Visible);
+            Assert.True(mediaSelector.Enabled);
+
+            // 1 ページ目のみ選択可能な状態
+            var pages = mediaSelector.ImagePageCombo.Items;
+            Assert.Equal(new[] { "1" }, pages.Cast<object>().Select(x => x.ToString()));
+
+            // 1 ページ目が表示されている
+            Assert.Equal("1", mediaSelector.ImagePageCombo.Text);
+            Assert.Equal("", mediaSelector.ImagefilePathText.Text);
+            Assert.Null(mediaSelector.ImageSelectedPicture.Image);
+        }
 
-                Assert.Raises<EventArgs>(
-                    x => mediaSelector.BeginSelecting += x,
-                    x => mediaSelector.BeginSelecting -= x,
-                    () => mediaSelector.BeginSelection()
-                );
+        [Fact]
+        public void BeginSelection_FilePathTest()
+        {
+            using var twitter = new Twitter();
+            using var mediaSelector = new MediaSelector { Visible = false, Enabled = false };
+            twitter.Initialize("", "", "", 0L);
+            mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");
 
-                Assert.True(mediaSelector.Visible);
-                Assert.True(mediaSelector.Enabled);
+            var images = new[] { "Resources/re.gif" };
 
-                // 1 ページ目のみ選択可能な状態
-                var pages = mediaSelector.ImagePageCombo.Items;
-                Assert.Equal(new[] { "1" }, pages.Cast<object>().Select(x => x.ToString()));
+            Assert.Raises<EventArgs>(
+                x => mediaSelector.BeginSelecting += x,
+                x => mediaSelector.BeginSelecting -= x,
+                () => mediaSelector.BeginSelection(images)
+            );
 
-                // 1 ページ目が表示されている
-                Assert.Equal("1", mediaSelector.ImagePageCombo.Text);
-                Assert.Equal("", mediaSelector.ImagefilePathText.Text);
-                Assert.Null(mediaSelector.ImageSelectedPicture.Image);
-            }
+            Assert.True(mediaSelector.Visible);
+            Assert.True(mediaSelector.Enabled);
+
+            // 2 ページ目まで選択可能な状態
+            var pages = mediaSelector.ImagePageCombo.Items;
+            Assert.Equal(new[] { "1", "2" }, pages.Cast<object>().Select(x => x.ToString()));
+
+            // 1 ページ目が表示されている
+            Assert.Equal("1", mediaSelector.ImagePageCombo.Text);
+            Assert.Equal(Path.GetFullPath("Resources/re.gif"), mediaSelector.ImagefilePathText.Text);
+
+            using var imageStream = File.OpenRead("Resources/re.gif");
+            using var image = MemoryImage.CopyFromStream(imageStream);
+            Assert.Equal(image, mediaSelector.ImageSelectedPicture.Image);
         }
 
         [Fact]
-        public void BeginSelection_FilePathTest()
+        public void BeginSelection_MemoryImageTest()
         {
-            using (var twitter = new Twitter())
-            using (var mediaSelector = new MediaSelector { Visible = false, Enabled = false })
-            {
-                twitter.Initialize("", "", "", 0L);
-                mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");
-
-                var images = new[] { "Resources/re.gif" };
+            using var twitter = new Twitter();
+            using var mediaSelector = new MediaSelector { Visible = false, Enabled = false };
+            twitter.Initialize("", "", "", 0L);
+            mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");
 
+            using (var bitmap = new Bitmap(width: 200, height: 200))
+            {
                 Assert.Raises<EventArgs>(
                     x => mediaSelector.BeginSelecting += x,
                     x => mediaSelector.BeginSelecting -= x,
-                    () => mediaSelector.BeginSelection(images)
+                    () => mediaSelector.BeginSelection(bitmap)
                 );
+            }
 
-                Assert.True(mediaSelector.Visible);
-                Assert.True(mediaSelector.Enabled);
+            Assert.True(mediaSelector.Visible);
+            Assert.True(mediaSelector.Enabled);
 
-                // 2 ページ目まで選択可能な状態
-                var pages = mediaSelector.ImagePageCombo.Items;
-                Assert.Equal(new[] { "1", "2" }, pages.Cast<object>().Select(x => x.ToString()));
+            // 2 ページ目まで選択可能な状態
+            var pages = mediaSelector.ImagePageCombo.Items;
+            Assert.Equal(new[] { "1", "2" }, pages.Cast<object>().Select(x => x.ToString()));
 
-                // 1 ページ目が表示されている
-                Assert.Equal("1", mediaSelector.ImagePageCombo.Text);
-                Assert.Equal(Path.GetFullPath("Resources/re.gif"), mediaSelector.ImagefilePathText.Text);
+            // 1 ページ目が表示されている
+            Assert.Equal("1", mediaSelector.ImagePageCombo.Text);
+            Assert.Matches(@"^<>MemoryImage://\d+.png$", mediaSelector.ImagefilePathText.Text);
 
-                using (var imageStream = File.OpenRead("Resources/re.gif"))
-                using (var image = MemoryImage.CopyFromStream(imageStream))
-                {
-                    Assert.Equal(image, mediaSelector.ImageSelectedPicture.Image);
-                }
-            }
-        }
-
-        [Fact]
-        public void BeginSelection_MemoryImageTest()
-        {
-            using (var twitter = new Twitter())
-            using (var mediaSelector = new MediaSelector { Visible = false, Enabled = false })
+            using (var bitmap = new Bitmap(width: 200, height: 200))
             {
-                twitter.Initialize("", "", "", 0L);
-                mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");
-
-                using (var bitmap = new Bitmap(width: 200, height: 200))
-                {
-                    Assert.Raises<EventArgs>(
-                        x => mediaSelector.BeginSelecting += x,
-                        x => mediaSelector.BeginSelecting -= x,
-                        () => mediaSelector.BeginSelection(bitmap)
-                    );
-                }
-
-                Assert.True(mediaSelector.Visible);
-                Assert.True(mediaSelector.Enabled);
-
-                // 2 ページ目まで選択可能な状態
-                var pages = mediaSelector.ImagePageCombo.Items;
-                Assert.Equal(new[] { "1", "2" }, pages.Cast<object>().Select(x => x.ToString()));
-
-                // 1 ページ目が表示されている
-                Assert.Equal("1", mediaSelector.ImagePageCombo.Text);
-                Assert.Matches(@"^<>MemoryImage://\d+.png$", mediaSelector.ImagefilePathText.Text);
-
-                using (var bitmap = new Bitmap(width: 200, height: 200))
-                using (var image = MemoryImage.CopyFromImage(bitmap))
-                {
-                    Assert.Equal(image, mediaSelector.ImageSelectedPicture.Image);
-                }
+                using var image = MemoryImage.CopyFromImage(bitmap);
+                Assert.Equal(image, mediaSelector.ImageSelectedPicture.Image);
             }
         }
 
         [Fact]
         public void BeginSelection_MultiImageTest()
         {
-            using (var twitter = new Twitter())
-            using (var mediaSelector = new MediaSelector { Visible = false, Enabled = false })
-            {
-                twitter.Initialize("", "", "", 0L);
-                mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");
+            using var twitter = new Twitter();
+            using var mediaSelector = new MediaSelector { Visible = false, Enabled = false };
+            twitter.Initialize("", "", "", 0L);
+            mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");
 
-                var images = new[] { "Resources/re.gif", "Resources/re1.png" };
-                mediaSelector.BeginSelection(images);
+            var images = new[] { "Resources/re.gif", "Resources/re1.png" };
+            mediaSelector.BeginSelection(images);
 
-                // 3 ページ目まで選択可能な状態
-                var pages = mediaSelector.ImagePageCombo.Items;
-                Assert.Equal(new[] { "1", "2", "3" }, pages.Cast<object>().Select(x => x.ToString()));
+            // 3 ページ目まで選択可能な状態
+            var pages = mediaSelector.ImagePageCombo.Items;
+            Assert.Equal(new[] { "1", "2", "3" }, pages.Cast<object>().Select(x => x.ToString()));
 
-                // 1 ページ目が表示されている
-                Assert.Equal("1", mediaSelector.ImagePageCombo.Text);
-                Assert.Equal(Path.GetFullPath("Resources/re.gif"), mediaSelector.ImagefilePathText.Text);
+            // 1 ページ目が表示されている
+            Assert.Equal("1", mediaSelector.ImagePageCombo.Text);
+            Assert.Equal(Path.GetFullPath("Resources/re.gif"), mediaSelector.ImagefilePathText.Text);
 
-                using (var imageStream = File.OpenRead("Resources/re.gif"))
-                using (var image = MemoryImage.CopyFromStream(imageStream))
-                {
-                    Assert.Equal(image, mediaSelector.ImageSelectedPicture.Image);
-                }
-            }
+            using var imageStream = File.OpenRead("Resources/re.gif");
+            using var image = MemoryImage.CopyFromStream(imageStream);
+            Assert.Equal(image, mediaSelector.ImageSelectedPicture.Image);
         }
 
         [Fact]
         public void EndSelection_Test()
         {
-            using (var twitter = new Twitter())
-            using (var mediaSelector = new MediaSelector { Visible = false, Enabled = false })
-            {
-                twitter.Initialize("", "", "", 0L);
-                mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");
-                mediaSelector.BeginSelection(new[] { "Resources/re.gif" });
+            using var twitter = new Twitter();
+            using var mediaSelector = new MediaSelector { Visible = false, Enabled = false };
+            twitter.Initialize("", "", "", 0L);
+            mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");
+            mediaSelector.BeginSelection(new[] { "Resources/re.gif" });
 
-                var displayImage = mediaSelector.ImageSelectedPicture.Image; // 表示中の画像
+            var displayImage = mediaSelector.ImageSelectedPicture.Image; // 表示中の画像
 
-                Assert.Raises<EventArgs>(
-                    x => mediaSelector.EndSelecting += x,
-                    x => mediaSelector.EndSelecting -= x,
-                    () => mediaSelector.EndSelection()
-                );
+            Assert.Raises<EventArgs>(
+                x => mediaSelector.EndSelecting += x,
+                x => mediaSelector.EndSelecting -= x,
+                () => mediaSelector.EndSelection()
+            );
 
-                Assert.False(mediaSelector.Visible);
-                Assert.False(mediaSelector.Enabled);
+            Assert.False(mediaSelector.Visible);
+            Assert.False(mediaSelector.Enabled);
 
-                Assert.True(displayImage.IsDisposed);
-            }
+            Assert.True(displayImage.IsDisposed);
         }
 
         [Fact]
         public void PageChange_Test()
         {
-            using (var twitter = new Twitter())
-            using (var mediaSelector = new MediaSelector { Visible = false, Enabled = false })
-            {
-                twitter.Initialize("", "", "", 0L);
-                mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");
+            using var twitter = new Twitter();
+            using var mediaSelector = new MediaSelector { Visible = false, Enabled = false };
+            twitter.Initialize("", "", "", 0L);
+            mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");
 
-                var images = new[] { "Resources/re.gif", "Resources/re1.png" };
-                mediaSelector.BeginSelection(images);
+            var images = new[] { "Resources/re.gif", "Resources/re1.png" };
+            mediaSelector.BeginSelection(images);
 
-                mediaSelector.ImagePageCombo.SelectedIndex = 0;
+            mediaSelector.ImagePageCombo.SelectedIndex = 0;
 
-                // 1 ページ目
-                Assert.Equal("1", mediaSelector.ImagePageCombo.Text);
-                Assert.Equal(Path.GetFullPath("Resources/re.gif"), mediaSelector.ImagefilePathText.Text);
+            // 1 ページ目
+            Assert.Equal("1", mediaSelector.ImagePageCombo.Text);
+            Assert.Equal(Path.GetFullPath("Resources/re.gif"), mediaSelector.ImagefilePathText.Text);
 
-                using (var imageStream = File.OpenRead("Resources/re.gif"))
-                using (var image = MemoryImage.CopyFromStream(imageStream))
-                {
-                    Assert.Equal(image, mediaSelector.ImageSelectedPicture.Image);
-                }
+            using (var imageStream = File.OpenRead("Resources/re.gif"))
+            {
+                using var image = MemoryImage.CopyFromStream(imageStream);
+                Assert.Equal(image, mediaSelector.ImageSelectedPicture.Image);
+            }
 
-                mediaSelector.ImagePageCombo.SelectedIndex = 1;
+            mediaSelector.ImagePageCombo.SelectedIndex = 1;
 
-                // 2 ページ目
-                Assert.Equal("2", mediaSelector.ImagePageCombo.Text);
-                Assert.Equal(Path.GetFullPath("Resources/re1.png"), mediaSelector.ImagefilePathText.Text);
+            // 2 ページ目
+            Assert.Equal("2", mediaSelector.ImagePageCombo.Text);
+            Assert.Equal(Path.GetFullPath("Resources/re1.png"), mediaSelector.ImagefilePathText.Text);
 
-                using (var imageStream = File.OpenRead("Resources/re1.png"))
-                using (var image = MemoryImage.CopyFromStream(imageStream))
-                {
-                    Assert.Equal(image, mediaSelector.ImageSelectedPicture.Image);
-                }
+            using (var imageStream = File.OpenRead("Resources/re1.png"))
+            {
+                using var image = MemoryImage.CopyFromStream(imageStream);
+                Assert.Equal(image, mediaSelector.ImageSelectedPicture.Image);
+            }
 
-                mediaSelector.ImagePageCombo.SelectedIndex = 2;
+            mediaSelector.ImagePageCombo.SelectedIndex = 2;
 
-                // 3 ページ目 (新規ページ)
-                Assert.Equal("3", mediaSelector.ImagePageCombo.Text);
-                Assert.Equal("", mediaSelector.ImagefilePathText.Text);
-                Assert.Null(mediaSelector.ImageSelectedPicture.Image);
-            }
+            // 3 ページ目 (新規ページ)
+            Assert.Equal("3", mediaSelector.ImagePageCombo.Text);
+            Assert.Equal("", mediaSelector.ImagefilePathText.Text);
+            Assert.Null(mediaSelector.ImageSelectedPicture.Image);
         }
 
         [Fact]
         public void PageChange_AlternativeTextTest()
         {
-            using (var twitter = new Twitter())
-            using (var mediaSelector = new MediaSelector { Visible = false, Enabled = false })
-            {
-                twitter.Initialize("", "", "", 0L);
-                mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");
-
-                var images = new[] { "Resources/re.gif", "Resources/re1.png" };
-                mediaSelector.BeginSelection(images);
-
-                // 1 ページ目
-                mediaSelector.ImagePageCombo.SelectedIndex = 0;
-                mediaSelector.AlternativeTextBox.Text = "Page 1";
-                mediaSelector.ValidateChildren();
-
-                // 2 ページ目
-                mediaSelector.ImagePageCombo.SelectedIndex = 1;
-                mediaSelector.AlternativeTextBox.Text = "Page 2";
-                mediaSelector.ValidateChildren();
-
-                // 3 ページ目 (新規ページ)
-                mediaSelector.ImagePageCombo.SelectedIndex = 2;
-                mediaSelector.AlternativeTextBox.Text = "Page 3";
-                mediaSelector.ValidateChildren();
-
-                mediaSelector.ImagePageCombo.SelectedIndex = 0;
-                Assert.Equal("Page 1", mediaSelector.AlternativeTextBox.Text);
-
-                mediaSelector.ImagePageCombo.SelectedIndex = 1;
-                Assert.Equal("Page 2", mediaSelector.AlternativeTextBox.Text);
-
-                // 画像が指定されていないページは入力した代替テキストも保持されない
-                mediaSelector.ImagePageCombo.SelectedIndex = 2;
-                Assert.Equal("", mediaSelector.AlternativeTextBox.Text);
-            }
+            using var twitter = new Twitter();
+            using var mediaSelector = new MediaSelector { Visible = false, Enabled = false };
+            twitter.Initialize("", "", "", 0L);
+            mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");
+
+            var images = new[] { "Resources/re.gif", "Resources/re1.png" };
+            mediaSelector.BeginSelection(images);
+
+            // 1 ページ目
+            mediaSelector.ImagePageCombo.SelectedIndex = 0;
+            mediaSelector.AlternativeTextBox.Text = "Page 1";
+            mediaSelector.ValidateChildren();
+
+            // 2 ページ目
+            mediaSelector.ImagePageCombo.SelectedIndex = 1;
+            mediaSelector.AlternativeTextBox.Text = "Page 2";
+            mediaSelector.ValidateChildren();
+
+            // 3 ページ目 (新規ページ)
+            mediaSelector.ImagePageCombo.SelectedIndex = 2;
+            mediaSelector.AlternativeTextBox.Text = "Page 3";
+            mediaSelector.ValidateChildren();
+
+            mediaSelector.ImagePageCombo.SelectedIndex = 0;
+            Assert.Equal("Page 1", mediaSelector.AlternativeTextBox.Text);
+
+            mediaSelector.ImagePageCombo.SelectedIndex = 1;
+            Assert.Equal("Page 2", mediaSelector.AlternativeTextBox.Text);
+
+            // 画像が指定されていないページは入力した代替テキストも保持されない
+            mediaSelector.ImagePageCombo.SelectedIndex = 2;
+            Assert.Equal("", mediaSelector.AlternativeTextBox.Text);
         }
 
         [Fact]
         public void PageChange_ImageDisposeTest()
         {
-            using (var twitter = new Twitter())
-            using (var mediaSelector = new MediaSelector { Visible = false, Enabled = false })
-            {
-                twitter.Initialize("", "", "", 0L);
-                mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");
+            using var twitter = new Twitter();
+            using var mediaSelector = new MediaSelector { Visible = false, Enabled = false };
+            twitter.Initialize("", "", "", 0L);
+            mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");
 
-                var images = new[] { "Resources/re.gif", "Resources/re1.png" };
-                mediaSelector.BeginSelection(images);
+            var images = new[] { "Resources/re.gif", "Resources/re1.png" };
+            mediaSelector.BeginSelection(images);
 
-                mediaSelector.ImagePageCombo.SelectedIndex = 0;
+            mediaSelector.ImagePageCombo.SelectedIndex = 0;
 
-                // 1 ページ目
-                var page1Image = mediaSelector.ImageSelectedPicture.Image;
+            // 1 ページ目
+            var page1Image = mediaSelector.ImageSelectedPicture.Image;
 
-                mediaSelector.ImagePageCombo.SelectedIndex = 1;
+            mediaSelector.ImagePageCombo.SelectedIndex = 1;
 
-                // 2 ページ目
-                var page2Image = mediaSelector.ImageSelectedPicture.Image;
-                Assert.True(page1Image.IsDisposed); // 前ページの画像が破棄されているか
+            // 2 ページ目
+            var page2Image = mediaSelector.ImageSelectedPicture.Image;
+            Assert.True(page1Image.IsDisposed); // 前ページの画像が破棄されているか
 
-                mediaSelector.ImagePageCombo.SelectedIndex = 2;
+            mediaSelector.ImagePageCombo.SelectedIndex = 2;
 
-                // 3 ページ目 (新規ページ)
-                Assert.True(page2Image.IsDisposed); // 前ページの画像が破棄されているか
-            }
+            // 3 ページ目 (新規ページ)
+            Assert.True(page2Image.IsDisposed); // 前ページの画像が破棄されているか
         }
 
         [Fact]
         public void ImagePathInput_Test()
         {
-            using (var twitter = new Twitter())
-            using (var mediaSelector = new MediaSelector { Visible = false, Enabled = false })
+            using var twitter = new Twitter();
+            using var mediaSelector = new MediaSelector { Visible = false, Enabled = false };
+            twitter.Initialize("", "", "", 0L);
+            mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");
+            mediaSelector.BeginSelection();
+
+            // 画像のファイルパスを入力
+            mediaSelector.ImagefilePathText.Text = Path.GetFullPath("Resources/re1.png");
+            TestUtils.Validate(mediaSelector.ImagefilePathText);
+
+            // 入力したパスの画像が表示される
+            using (var imageStream = File.OpenRead("Resources/re1.png"))
             {
-                twitter.Initialize("", "", "", 0L);
-                mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");
-                mediaSelector.BeginSelection();
-
-                // 画像のファイルパスを入力
-                mediaSelector.ImagefilePathText.Text = Path.GetFullPath("Resources/re1.png");
-                TestUtils.Validate(mediaSelector.ImagefilePathText);
-
-                // 入力したパスの画像が表示される
-                using (var imageStream = File.OpenRead("Resources/re1.png"))
-                using (var image = MemoryImage.CopyFromStream(imageStream))
-                {
-                    Assert.Equal(image, mediaSelector.ImageSelectedPicture.Image);
-                }
-
-                // 2 ページ目まで選択可能な状態
-                var pages = mediaSelector.ImagePageCombo.Items;
-                Assert.Equal(new[] { "1", "2" }, pages.Cast<object>().Select(x => x.ToString()));
+                using var image = MemoryImage.CopyFromStream(imageStream);
+                Assert.Equal(image, mediaSelector.ImageSelectedPicture.Image);
             }
+
+            // 2 ページ目まで選択可能な状態
+            var pages = mediaSelector.ImagePageCombo.Items;
+            Assert.Equal(new[] { "1", "2" }, pages.Cast<object>().Select(x => x.ToString()));
         }
 
         [Fact]
         public void ImagePathInput_ReplaceFileMediaItemTest()
         {
-            using (var twitter = new Twitter())
-            using (var mediaSelector = new MediaSelector { Visible = false, Enabled = false })
-            {
-                twitter.Initialize("", "", "", 0L);
-                mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");
-
-                mediaSelector.BeginSelection(new[] { "Resources/re.gif" });
+            using var twitter = new Twitter();
+            using var mediaSelector = new MediaSelector { Visible = false, Enabled = false };
+            twitter.Initialize("", "", "", 0L);
+            mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");
 
-                // 既に入力されているファイルパスの画像
-                var image1 = mediaSelector.ImageSelectedPicture.Image;
+            mediaSelector.BeginSelection(new[] { "Resources/re.gif" });
 
-                // 別の画像のファイルパスを入力
-                mediaSelector.ImagefilePathText.Text = Path.GetFullPath("Resources/re1.png");
-                TestUtils.Validate(mediaSelector.ImagefilePathText);
+            // 既に入力されているファイルパスの画像
+            var image1 = mediaSelector.ImageSelectedPicture.Image;
 
-                // 入力したパスの画像が表示される
-                using (var imageStream = File.OpenRead("Resources/re1.png"))
-                using (var image2 = MemoryImage.CopyFromStream(imageStream))
-                {
-                    Assert.Equal(image2, mediaSelector.ImageSelectedPicture.Image);
-                }
+            // 別の画像のファイルパスを入力
+            mediaSelector.ImagefilePathText.Text = Path.GetFullPath("Resources/re1.png");
+            TestUtils.Validate(mediaSelector.ImagefilePathText);
 
-                // 最初に入力されていたファイルパスの表示用の MemoryImage は破棄される
-                Assert.True(image1.IsDisposed);
+            // 入力したパスの画像が表示される
+            using (var imageStream = File.OpenRead("Resources/re1.png"))
+            {
+                using var image2 = MemoryImage.CopyFromStream(imageStream);
+                Assert.Equal(image2, mediaSelector.ImageSelectedPicture.Image);
             }
+
+            // 最初に入力されていたファイルパスの表示用の MemoryImage は破棄される
+            Assert.True(image1.IsDisposed);
         }
 
         [Fact]
         public void ImagePathInput_ReplaceMemoryImageMediaItemTest()
         {
-            using (var twitter = new Twitter())
-            using (var mediaSelector = new MediaSelector { Visible = false, Enabled = false })
-            {
-                twitter.Initialize("", "", "", 0L);
-                mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");
-
-                using (var bitmap = new Bitmap(width: 200, height: 200))
-                {
-                    mediaSelector.BeginSelection(bitmap);
-                }
-
-                // 既に入力されているファイルパスの画像
-                var image1 = mediaSelector.ImageSelectedPicture.Image;
-
-                // 内部で保持されている MemoryImageMediaItem を取り出す
-                var selectedMedia = mediaSelector.ImagePageCombo.SelectedItem;
-                var mediaProperty = selectedMedia.GetType().GetProperty("Item");
-                var mediaItem = (MemoryImageMediaItem)mediaProperty.GetValue(selectedMedia);
-
-                // 別の画像のファイルパスを入力
-                mediaSelector.ImagefilePathText.Text = Path.GetFullPath("Resources/re1.png");
-                TestUtils.Validate(mediaSelector.ImagefilePathText);
-
-                // 入力したパスの画像が表示される
-                using (var imageStream = File.OpenRead("Resources/re1.png"))
-                using (var image2 = MemoryImage.CopyFromStream(imageStream))
-                {
-                    Assert.Equal(image2, mediaSelector.ImageSelectedPicture.Image);
-                }
-
-                // 最初に入力されていたファイルパスの表示用の MemoryImage は破棄される
-                Assert.True(image1.IsDisposed);
-
-                // 参照されなくなった MemoryImageMediaItem も破棄される
-                Assert.True(mediaItem.IsDisposed);
-            }
-        }
+            using var twitter = new Twitter();
+            using var mediaSelector = new MediaSelector { Visible = false, Enabled = false };
+            twitter.Initialize("", "", "", 0L);
+            mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");
 
-        [Fact]
-        public void ImageServiceChange_Test()
-        {
-            using (var twitter = new Twitter())
-            using (var mediaSelector = new MediaSelector { Visible = false, Enabled = false })
+            using (var bitmap = new Bitmap(width: 200, height: 200))
             {
-                twitter.Initialize("", "", "", 0L);
-                mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");
+                mediaSelector.BeginSelection(bitmap);
+            }
 
-                Assert.Equal("Twitter", mediaSelector.ServiceName);
+            // 既に入力されているファイルパスの画像
+            var image1 = mediaSelector.ImageSelectedPicture.Image;
 
-                mediaSelector.BeginSelection(new[] { "Resources/re.gif", "Resources/re1.png" });
+            // 内部で保持されている MemoryImageMediaItem を取り出す
+            var selectedMedia = mediaSelector.ImagePageCombo.SelectedItem;
+            var mediaProperty = selectedMedia.GetType().GetProperty("Item");
+            var mediaItem = (MemoryImageMediaItem)mediaProperty.GetValue(selectedMedia);
 
-                // 3 ページ目まで選択可能な状態
-                var pages = mediaSelector.ImagePageCombo.Items;
-                Assert.Equal(new[] { "1", "2", "3" }, pages.Cast<object>().Select(x => x.ToString()));
-                Assert.True(mediaSelector.ImagePageCombo.Enabled);
+            // 別の画像のファイルパスを入力
+            mediaSelector.ImagefilePathText.Text = Path.GetFullPath("Resources/re1.png");
+            TestUtils.Validate(mediaSelector.ImagefilePathText);
 
-                // 投稿先を Imgur に変更
-                var imgurIndex = mediaSelector.ImageServiceCombo.Items.IndexOf("Imgur");
-                Assert.Raises<EventArgs>(
-                    x => mediaSelector.SelectedServiceChanged += x,
-                    x => mediaSelector.SelectedServiceChanged -= x,
-                    () => mediaSelector.ImageServiceCombo.SelectedIndex = imgurIndex
-                );
+            // 入力したパスの画像が表示される
+            using (var imageStream = File.OpenRead("Resources/re1.png"))
+            {
+                using var image2 = MemoryImage.CopyFromStream(imageStream);
+                Assert.Equal(image2, mediaSelector.ImageSelectedPicture.Image);
+            }
 
-                // 1 ページ目のみ選択可能な状態 (Disabled)
-                pages = mediaSelector.ImagePageCombo.Items;
-                Assert.Equal(new[] { "1" }, pages.Cast<object>().Select(x => x.ToString()));
-                Assert.False(mediaSelector.ImagePageCombo.Enabled);
+            // 最初に入力されていたファイルパスの表示用の MemoryImage は破棄される
+            Assert.True(image1.IsDisposed);
 
-                // 投稿先を Twitter に変更
-                mediaSelector.ImageServiceCombo.SelectedIndex =
-                    mediaSelector.ImageServiceCombo.Items.IndexOf("Twitter");
+            // 参照されなくなった MemoryImageMediaItem も破棄される
+            Assert.True(mediaItem.IsDisposed);
+        }
 
-                // 2 ページ目まで選択可能な状態
-                pages = mediaSelector.ImagePageCombo.Items;
-                Assert.Equal(new[] { "1", "2" }, pages.Cast<object>().Select(x => x.ToString()));
-                Assert.True(mediaSelector.ImagePageCombo.Enabled);
-            }
+        [Fact]
+        public void ImageServiceChange_Test()
+        {
+            using var twitter = new Twitter();
+            using var mediaSelector = new MediaSelector { Visible = false, Enabled = false };
+            twitter.Initialize("", "", "", 0L);
+            mediaSelector.Initialize(twitter, TwitterConfiguration.DefaultConfiguration(), "Twitter");
+
+            Assert.Equal("Twitter", mediaSelector.ServiceName);
+
+            mediaSelector.BeginSelection(new[] { "Resources/re.gif", "Resources/re1.png" });
+
+            // 3 ページ目まで選択可能な状態
+            var pages = mediaSelector.ImagePageCombo.Items;
+            Assert.Equal(new[] { "1", "2", "3" }, pages.Cast<object>().Select(x => x.ToString()));
+            Assert.True(mediaSelector.ImagePageCombo.Enabled);
+
+            // 投稿先を Imgur に変更
+            var imgurIndex = mediaSelector.ImageServiceCombo.Items.IndexOf("Imgur");
+            Assert.Raises<EventArgs>(
+                x => mediaSelector.SelectedServiceChanged += x,
+                x => mediaSelector.SelectedServiceChanged -= x,
+                () => mediaSelector.ImageServiceCombo.SelectedIndex = imgurIndex
+            );
+
+            // 1 ページ目のみ選択可能な状態 (Disabled)
+            pages = mediaSelector.ImagePageCombo.Items;
+            Assert.Equal(new[] { "1" }, pages.Cast<object>().Select(x => x.ToString()));
+            Assert.False(mediaSelector.ImagePageCombo.Enabled);
+
+            // 投稿先を Twitter に変更
+            mediaSelector.ImageServiceCombo.SelectedIndex =
+                mediaSelector.ImageServiceCombo.Items.IndexOf("Twitter");
+
+            // 2 ページ目まで選択可能な状態
+            pages = mediaSelector.ImagePageCombo.Items;
+            Assert.Equal(new[] { "1", "2" }, pages.Cast<object>().Select(x => x.ToString()));
+            Assert.True(mediaSelector.ImagePageCombo.Enabled);
         }
     }
 }
index 867c0db..09d6780 100644 (file)
@@ -79,13 +79,13 @@ namespace OpenTween.Api
             var paramWithToken = param.Concat(this.CreateAccessTokenParams());
 
             var requestUri = new Uri(new Uri(ApiBase, endpoint), "?" + MyCommon.BuildQueryString(paramWithToken));
+            using var request = new HttpRequestMessage(HttpMethod.Get, requestUri);
 
-            using (var request = new HttpRequestMessage(HttpMethod.Get, requestUri))
-            using (var response = await this.http.SendAsync(request).ConfigureAwait(false))
-            {
-                return await response.Content.ReadAsStringAsync()
-                    .ConfigureAwait(false);
-            }
+            using var response = await this.http.SendAsync(request)
+                .ConfigureAwait(false);
+
+            return await response.Content.ReadAsStringAsync()
+                .ConfigureAwait(false);
         }
 
         public async Task<string> GetAccessTokenAsync(string username, string password)
@@ -99,43 +99,39 @@ namespace OpenTween.Api
 
             var endpoint = new Uri(ApiBase, "/oauth/access_token");
 
-            using (var request = new HttpRequestMessage(HttpMethod.Post, endpoint))
-            using (var postContent = new FormUrlEncodedContent(param))
-            {
-                var authzParam = ApplicationSettings.BitlyClientId + ":" + ApplicationSettings.BitlyClientSecret;
-                request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes(authzParam)));
+            using var request = new HttpRequestMessage(HttpMethod.Post, endpoint);
+            using var postContent = new FormUrlEncodedContent(param);
 
-                request.Content = postContent;
+            var authzParam = ApplicationSettings.BitlyClientId + ":" + ApplicationSettings.BitlyClientSecret;
+            request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes(authzParam)));
 
-                using (var response = await this.http.SendAsync(request).ConfigureAwait(false))
-                {
-                    var responseBytes = await response.Content.ReadAsByteArrayAsync()
-                        .ConfigureAwait(false);
+            request.Content = postContent;
 
-                    return this.ParseOAuthCredential(responseBytes);
-                }
-            }
+            using var response = await this.http.SendAsync(request)
+                .ConfigureAwait(false);
+            var responseBytes = await response.Content.ReadAsByteArrayAsync()
+                .ConfigureAwait(false);
+
+            return this.ParseOAuthCredential(responseBytes);
         }
 
         private string ParseOAuthCredential(byte[] responseBytes)
         {
-            using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(responseBytes, XmlDictionaryReaderQuotas.Max))
-            {
-                var xElm = XElement.Load(jsonReader);
+            using var jsonReader = JsonReaderWriterFactory.CreateJsonReader(responseBytes, XmlDictionaryReaderQuotas.Max);
+            var xElm = XElement.Load(jsonReader);
 
-                var statusCode = xElm.Element("status_code")?.Value ?? "200";
-                if (statusCode != "200")
-                {
-                    var statusText = xElm.Element("status_txt")?.Value;
-                    throw new WebApiException(statusText ?? $"status_code = {statusCode}");
-                }
+            var statusCode = xElm.Element("status_code")?.Value ?? "200";
+            if (statusCode != "200")
+            {
+                var statusText = xElm.Element("status_txt")?.Value;
+                throw new WebApiException(statusText ?? $"status_code = {statusCode}");
+            }
 
-                var accessToken = xElm.Element("access_token")?.Value;
-                if (accessToken == null)
-                    throw new WebApiException("Property `access_token` required");
+            var accessToken = xElm.Element("access_token")?.Value;
+            if (accessToken == null)
+                throw new WebApiException("Property `access_token` required");
 
-                return accessToken;
-            }
+            return accessToken;
         }
 
         private IEnumerable<KeyValuePair<string, string>> CreateAccessTokenParams()
index 5d035bf..57f1bb8 100644 (file)
@@ -69,34 +69,28 @@ namespace OpenTween.Api
 
             var requestUri = new Uri(TranslateEndpoint, "?" + MyCommon.BuildQueryString(param));
 
-            using (var request = new HttpRequestMessage(HttpMethod.Post, requestUri))
-            {
-                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", this.AccessToken);
+            using var request = new HttpRequestMessage(HttpMethod.Post, requestUri);
+            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", this.AccessToken);
+
+            var escapedText = JsonUtils.EscapeJsonString(text);
+            var json = $@"[{{""Text"": ""{escapedText}""}}]";
 
-                var escapedText = JsonUtils.EscapeJsonString(text);
-                var json = $@"[{{""Text"": ""{escapedText}""}}]";
+            using var body = new StringContent(json, Encoding.UTF8, "application/json");
+            request.Content = body;
 
-                using (var body = new StringContent(json, Encoding.UTF8, "application/json"))
-                {
-                    request.Content = body;
+            using var response = await this.Http.SendAsync(request)
+                .ConfigureAwait(false);
 
-                    using (var response = await this.Http.SendAsync(request).ConfigureAwait(false))
-                    {
-                        response.EnsureSuccessStatusCode();
+            response.EnsureSuccessStatusCode();
 
-                        var responseJson = await response.Content.ReadAsByteArrayAsync()
-                            .ConfigureAwait(false);
+            var responseJson = await response.Content.ReadAsByteArrayAsync()
+                .ConfigureAwait(false);
 
-                        using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(responseJson, XmlDictionaryReaderQuotas.Max))
-                        {
-                            var xElm = XElement.Load(jsonReader);
-                            var transtlationTextElm = xElm.XPathSelectElement("/item/translations/item/text[1]");
+            using var jsonReader = JsonReaderWriterFactory.CreateJsonReader(responseJson, XmlDictionaryReaderQuotas.Max);
+            var xElm = XElement.Load(jsonReader);
+            var transtlationTextElm = xElm.XPathSelectElement("/item/translations/item/text[1]");
 
-                            return transtlationTextElm?.Value ?? "";
-                        }
-                    }
-                }
-            }
+            return transtlationTextElm?.Value ?? "";
         }
 
         public async Task UpdateAccessTokenIfExpired()
@@ -115,18 +109,16 @@ namespace OpenTween.Api
 
         internal virtual async Task<(string AccessToken, TimeSpan ExpiresIn)> GetAccessTokenAsync()
         {
-            using (var request = new HttpRequestMessage(HttpMethod.Post, IssueTokenEndpoint))
-            {
-                request.Headers.Add("Ocp-Apim-Subscription-Key", ApplicationSettings.TranslatorSubscriptionKey);
+            using var request = new HttpRequestMessage(HttpMethod.Post, IssueTokenEndpoint);
+            request.Headers.Add("Ocp-Apim-Subscription-Key", ApplicationSettings.TranslatorSubscriptionKey);
+
+            using var response = await this.Http.SendAsync(request)
+                .ConfigureAwait(false);
 
-                using (var response = await this.Http.SendAsync(request).ConfigureAwait(false))
-                {
-                    var accessToken = await response.Content.ReadAsStringAsync()
-                        .ConfigureAwait(false);
+            var accessToken = await response.Content.ReadAsStringAsync()
+                .ConfigureAwait(false);
 
-                    return (accessToken, TimeSpan.FromMinutes(10));
-                }
-            }
+            return (accessToken, TimeSpan.FromMinutes(10));
         }
     }
 }
index 0f6bb4c..eaf3a6f 100644 (file)
@@ -53,22 +53,21 @@ namespace OpenTween.Api
         {
             try
             {
-                using (var stream = await this.streamOpener().ConfigureAwait(false))
-                using (var reader = new StreamReader(stream))
+                using var stream = await this.streamOpener().ConfigureAwait(false);
+                using var reader = new StreamReader(stream);
+
+                while (!reader.EndOfStream)
                 {
-                    while (!reader.EndOfStream)
-                    {
-                        cancellationToken.ThrowIfCancellationRequested();
+                    cancellationToken.ThrowIfCancellationRequested();
 
-                        var line = await reader.ReadLineAsync()
-                            .ConfigureAwait(false);
+                    var line = await reader.ReadLineAsync()
+                        .ConfigureAwait(false);
 
-                        var message = ParseLine(line);
+                    var message = ParseLine(line);
 
-                        observer.OnNext(message);
-                    }
-                    observer.OnCompleted();
+                    observer.OnNext(message);
                 }
+                observer.OnCompleted();
             }
             catch (Exception ex)
             {
@@ -90,27 +89,25 @@ namespace OpenTween.Api
             try
             {
                 var bytes = Encoding.UTF8.GetBytes(line);
-                using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(bytes, XmlDictionaryReaderQuotas.Max))
-                {
-                    var xElm = XElement.Load(jsonReader);
+                using var jsonReader = JsonReaderWriterFactory.CreateJsonReader(bytes, XmlDictionaryReaderQuotas.Max);
+                var xElm = XElement.Load(jsonReader);
 
-                    if (xElm.Element("text") != null)
-                        return StreamMessageStatus.ParseJson(line);
+                if (xElm.Element("text") != null)
+                    return StreamMessageStatus.ParseJson(line);
 
-                    if (xElm.Element("delete") != null)
-                        return StreamMessageDelete.ParseJson(line);
+                if (xElm.Element("delete") != null)
+                    return StreamMessageDelete.ParseJson(line);
 
-                    if (xElm.Element("event") != null)
-                        return StreamMessageEvent.ParseJson(line);
+                if (xElm.Element("event") != null)
+                    return StreamMessageEvent.ParseJson(line);
 
-                    if (xElm.Element("direct_message") != null)
-                        return StreamMessageDirectMessage.ParseJson(line);
+                if (xElm.Element("direct_message") != null)
+                    return StreamMessageDirectMessage.ParseJson(line);
 
-                    if (xElm.Element("scrub_geo") != null)
-                        return StreamMessageScrubGeo.ParseJson(line);
+                if (xElm.Element("scrub_geo") != null)
+                    return StreamMessageScrubGeo.ParseJson(line);
 
-                    return new StreamMessageUnknown(line);
-                }
+                return new StreamMessageUnknown(line);
             }
             catch (XmlException)
             {
index 215bcae..dace571 100644 (file)
@@ -79,10 +79,11 @@ namespace OpenTween
 
             InitCulture();
 
-            // 同じ設定ファイルを使用する OpenTween プロセスの二重起動を防止する
-            var pt = MyCommon.settingPath.Replace("\\", "/") + "/" + ApplicationSettings.AssemblyName;
-            using (var mt = new Mutex(false, pt))
             {
+                // 同じ設定ファイルを使用する OpenTween プロセスの二重起動を防止する
+                var pt = MyCommon.settingPath.Replace("\\", "/") + "/" + ApplicationSettings.AssemblyName;
+                using var mt = new Mutex(false, pt);
+
                 if (!mt.WaitOne(0, false))
                 {
                     var text = string.Format(MyCommon.ReplaceAppName(Properties.Resources.StartupText1), ApplicationSettings.AssemblyName);
@@ -105,9 +106,9 @@ namespace OpenTween
                 Application.Run(new TweenMain());
 
                 mt.ReleaseMutex();
-
-                return 0;
             }
+
+            return 0;
         }
 
         /// <summary>
@@ -116,22 +117,19 @@ namespace OpenTween
         private static void WarnIfRunAsAdministrator()
         {
             // UAC が無効なシステムでは警告を表示しない
-            using (var lmKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
-            using (var systemKey = lmKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\"))
-            {
-                var enableLUA = (int?)systemKey?.GetValue("EnableLUA");
-                if (enableLUA != 1)
-                    return;
-            }
+            using var lmKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
+            using var systemKey = lmKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\");
+
+            var enableLUA = (int?)systemKey?.GetValue("EnableLUA");
+            if (enableLUA != 1)
+                return;
 
-            using (var currentIdentity = WindowsIdentity.GetCurrent())
+            using var currentIdentity = WindowsIdentity.GetCurrent();
+            var principal = new WindowsPrincipal(currentIdentity);
+            if (principal.IsInRole(WindowsBuiltInRole.Administrator))
             {
-                var principal = new WindowsPrincipal(currentIdentity);
-                if (principal.IsInRole(WindowsBuiltInRole.Administrator))
-                {
-                    var message = string.Format(Properties.Resources.WarnIfRunAsAdministrator_Message, ApplicationSettings.ApplicationName);
-                    MessageBox.Show(message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
-                }
+                var message = string.Format(Properties.Resources.WarnIfRunAsAdministrator_Message, ApplicationSettings.ApplicationName);
+                MessageBox.Show(message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
             }
         }
 
@@ -147,12 +145,11 @@ namespace OpenTween
             // .NET Framework 4.7.2 以降で動作しているかチェックする
             // 参照: https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/how-to-determine-which-versions-are-installed
 
-            using (var lmKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
-            using (var ndpKey = lmKey.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\"))
-            {
-                var releaseKey = (int)ndpKey.GetValue("Release");
-                return releaseKey >= 461808;
-            }
+            using var lmKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
+            using var ndpKey = lmKey.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\");
+
+            var releaseKey = (int)ndpKey.GetValue("Release");
+            return releaseKey >= 461808;
         }
 
         /// <summary>
index a24df9d..5919ece 100644 (file)
@@ -77,17 +77,15 @@ namespace OpenTween
         /// <returns>PIN文字列</returns>
         public static string DoAuth(IWin32Window owner, Uri authUri)
         {
-            using (var dialog = new AuthDialog())
-            {
-                dialog.AuthUrl = authUri.AbsoluteUri;
+            using var dialog = new AuthDialog();
+            dialog.AuthUrl = authUri.AbsoluteUri;
 
-                dialog.ShowDialog(owner);
+            dialog.ShowDialog(owner);
 
-                if (dialog.DialogResult == DialogResult.OK)
-                    return dialog.Pin;
-                else
-                    return null;
-            }
+            if (dialog.DialogResult == DialogResult.OK)
+                return dialog.Pin;
+            else
+                return null;
         }
     }
 }
index d0ae992..8ae866e 100644 (file)
@@ -152,31 +152,27 @@ namespace OpenTween.Connection
 
             public async Task<XDocument> UploadFileAsync(IMediaItem item, string title)
             {
-                using (var content = new MultipartFormDataContent())
-                using (var mediaStream = item.OpenRead())
-                using (var mediaContent = new StreamContent(mediaStream))
-                using (var titleContent = new StringContent(title))
-                {
-                    content.Add(mediaContent, "image", item.Name);
-                    content.Add(titleContent, "title");
-
-                    using (var request = new HttpRequestMessage(HttpMethod.Post, UploadEndpoint))
-                    {
-                        request.Headers.Authorization =
-                            new AuthenticationHeaderValue("Client-ID", ApplicationSettings.ImgurClientID);
-                        request.Content = content;
-
-                        using (var response = await this.http.SendAsync(request).ConfigureAwait(false))
-                        {
-                            response.EnsureSuccessStatusCode();
-
-                            using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
-                            {
-                                return XDocument.Load(stream);
-                            }
-                        }
-                    }
-                }
+                using var content = new MultipartFormDataContent();
+                using var mediaStream = item.OpenRead();
+                using var mediaContent = new StreamContent(mediaStream);
+                using var titleContent = new StringContent(title);
+
+                content.Add(mediaContent, "image", item.Name);
+                content.Add(titleContent, "title");
+
+                using var request = new HttpRequestMessage(HttpMethod.Post, UploadEndpoint);
+                request.Headers.Authorization = new AuthenticationHeaderValue("Client-ID", ApplicationSettings.ImgurClientID);
+                request.Content = content;
+
+                using var response = await this.http.SendAsync(request)
+                    .ConfigureAwait(false);
+
+                response.EnsureSuccessStatusCode();
+
+                using var stream = await response.Content.ReadAsStreamAsync()
+                    .ConfigureAwait(false);
+
+                return XDocument.Load(stream);
             }
         }
     }
index da5c882..25e88fb 100644 (file)
@@ -56,22 +56,20 @@ namespace OpenTween.Connection
             if (this.completed)
                 return this.instance;
 
-            using (var content = this.Response.Content)
-            {
-                var responseText = await content.ReadAsStringAsync()
-                    .ConfigureAwait(false);
+            using var content = this.Response.Content;
+            var responseText = await content.ReadAsStringAsync()
+                .ConfigureAwait(false);
 
-                try
-                {
-                    this.instance = MyCommon.CreateDataFromJson<T>(responseText);
-                    this.completed = true;
+            try
+            {
+                this.instance = MyCommon.CreateDataFromJson<T>(responseText);
+                this.completed = true;
 
-                    return this.instance;
-                }
-                catch (SerializationException ex)
-                {
-                    throw TwitterApiException.CreateFromException(ex, responseText);
-                }
+                return this.instance;
+            }
+            catch (SerializationException ex)
+            {
+                throw TwitterApiException.CreateFromException(ex, responseText);
             }
         }
 
@@ -89,10 +87,8 @@ namespace OpenTween.Connection
     {
         public static async Task IgnoreResponse<T>(this Task<LazyJson<T>> task)
         {
-            using (var lazyJson = await task.ConfigureAwait(false))
-            {
-                // レスポンスボディを読み込まず破棄する
-            }
+            using var lazyJson = await task.ConfigureAwait(false);
+            // レスポンスボディを読み込まず破棄する
         }
     }
 }
index 613e338..041fa6f 100644 (file)
@@ -173,32 +173,29 @@ namespace OpenTween.Connection
             {
                 // 参照: http://developers.mobypicture.com/documentation/2-0/upload/
 
-                using (var request = new HttpRequestMessage(HttpMethod.Post, UploadEndpoint))
-                using (var multipart = new MultipartFormDataContent())
-                {
-                    request.Content = multipart;
-
-                    using (var apiKeyContent = new StringContent(ApplicationSettings.MobypictureKey))
-                    using (var messageContent = new StringContent(message))
-                    using (var mediaStream = item.OpenRead())
-                    using (var mediaContent = new StreamContent(mediaStream))
-                    {
-                        multipart.Add(apiKeyContent, "key");
-                        multipart.Add(messageContent, "message");
-                        multipart.Add(mediaContent, "media", item.Name);
-
-                        using (var response = await this.http.SendAsync(request).ConfigureAwait(false))
-                        {
-                            var responseText = await response.Content.ReadAsStringAsync()
-                                .ConfigureAwait(false);
-
-                            if (!response.IsSuccessStatusCode)
-                                throw new WebApiException(response.StatusCode.ToString(), responseText);
-
-                            return XDocument.Parse(responseText);
-                        }
-                    }
-                }
+                using var request = new HttpRequestMessage(HttpMethod.Post, UploadEndpoint);
+                using var multipart = new MultipartFormDataContent();
+                request.Content = multipart;
+
+                using var apiKeyContent = new StringContent(ApplicationSettings.MobypictureKey);
+                using var messageContent = new StringContent(message);
+                using var mediaStream = item.OpenRead();
+                using var mediaContent = new StreamContent(mediaStream);
+
+                multipart.Add(apiKeyContent, "key");
+                multipart.Add(messageContent, "message");
+                multipart.Add(mediaContent, "media", item.Name);
+
+                using var response = await this.http.SendAsync(request)
+                    .ConfigureAwait(false);
+
+                var responseText = await response.Content.ReadAsStringAsync()
+                    .ConfigureAwait(false);
+
+                if (!response.IsSuccessStatusCode)
+                    throw new WebApiException(response.StatusCode.ToString(), responseText);
+
+                return XDocument.Parse(responseText);
             }
         }
     }
index d61924f..8431344 100644 (file)
@@ -122,11 +122,9 @@ namespace OpenTween.Connection
             if (!string.IsNullOrEmpty(tokenSecret))
                 key += MyCommon.UrlEncode(tokenSecret);
             // 鍵生成&署名生成
-            using (var hmac = new HMACSHA1(Encoding.ASCII.GetBytes(key)))
-            {
-                var hash = hmac.ComputeHash(Encoding.ASCII.GetBytes(signatureBase));
-                return Convert.ToBase64String(hash);
-            }
+            using var hmac = new HMACSHA1(Encoding.ASCII.GetBytes(key));
+            var hash = hmac.ComputeHash(Encoding.ASCII.GetBytes(signatureBase));
+            return Convert.ToBase64String(hash);
         }
     }
 }
index 86cf6b1..6e62623 100644 (file)
@@ -91,29 +91,26 @@ namespace OpenTween.Connection
 
             try
             {
-                using (var response = await this.http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)
-                    .ConfigureAwait(false))
-                {
-                    if (endpointName != null)
-                        MyCommon.TwitterApiInfo.UpdateFromHeader(response.Headers, endpointName);
+                using var response = await this.http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)
+                    .ConfigureAwait(false);
 
-                    await this.CheckStatusCode(response)
-                        .ConfigureAwait(false);
+                if (endpointName != null)
+                    MyCommon.TwitterApiInfo.UpdateFromHeader(response.Headers, endpointName);
 
-                    using (var content = response.Content)
-                    {
-                        var responseText = await content.ReadAsStringAsync()
-                            .ConfigureAwait(false);
-
-                        try
-                        {
-                            return MyCommon.CreateDataFromJson<T>(responseText);
-                        }
-                        catch (SerializationException ex)
-                        {
-                            throw TwitterApiException.CreateFromException(ex, responseText);
-                        }
-                    }
+                await this.CheckStatusCode(response)
+                    .ConfigureAwait(false);
+
+                using var content = response.Content;
+                var responseText = await content.ReadAsStringAsync()
+                    .ConfigureAwait(false);
+
+                try
+                {
+                    return MyCommon.CreateDataFromJson<T>(responseText);
+                }
+                catch (SerializationException ex)
+                {
+                    throw TwitterApiException.CreateFromException(ex, responseText);
                 }
             }
             catch (HttpRequestException ex)
@@ -204,36 +201,34 @@ namespace OpenTween.Connection
             var requestUri = new Uri(RestApiBase, uri);
             var request = new HttpRequestMessage(HttpMethod.Post, requestUri);
 
-            using (var postContent = new FormUrlEncodedContent(param))
-            {
-                request.Content = postContent;
+            using var postContent = new FormUrlEncodedContent(param);
+            request.Content = postContent;
 
-                HttpResponseMessage response = null;
-                try
-                {
-                    response = await this.http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)
-                        .ConfigureAwait(false);
+            HttpResponseMessage response = null;
+            try
+            {
+                response = await this.http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)
+                    .ConfigureAwait(false);
 
-                    await this.CheckStatusCode(response)
-                        .ConfigureAwait(false);
+                await this.CheckStatusCode(response)
+                    .ConfigureAwait(false);
 
-                    var result = new LazyJson<T>(response);
-                    response = null;
+                var result = new LazyJson<T>(response);
+                response = null;
 
-                    return result;
-                }
-                catch (HttpRequestException ex)
-                {
-                    throw TwitterApiException.CreateFromException(ex);
-                }
-                catch (OperationCanceledException ex)
-                {
-                    throw TwitterApiException.CreateFromException(ex);
-                }
-                finally
-                {
-                    response?.Dispose();
-                }
+                return result;
+            }
+            catch (HttpRequestException ex)
+            {
+                throw TwitterApiException.CreateFromException(ex);
+            }
+            catch (OperationCanceledException ex)
+            {
+                throw TwitterApiException.CreateFromException(ex);
+            }
+            finally
+            {
+                response?.Dispose();
             }
         }
 
@@ -242,47 +237,45 @@ namespace OpenTween.Connection
             var requestUri = new Uri(RestApiBase, uri);
             var request = new HttpRequestMessage(HttpMethod.Post, requestUri);
 
-            using (var postContent = new MultipartFormDataContent())
+            using var postContent = new MultipartFormDataContent();
+            if (param != null)
             {
-                if (param != null)
-                {
-                    foreach (var (key, value) in param)
-                        postContent.Add(new StringContent(value), key);
-                }
-                if (media != null)
-                {
-                    foreach (var (key, value) in media)
-                        postContent.Add(new StreamContent(value.OpenRead()), key, value.Name);
-                }
+                foreach (var (key, value) in param)
+                    postContent.Add(new StringContent(value), key);
+            }
+            if (media != null)
+            {
+                foreach (var (key, value) in media)
+                    postContent.Add(new StreamContent(value.OpenRead()), key, value.Name);
+            }
 
-                request.Content = postContent;
+            request.Content = postContent;
 
-                HttpResponseMessage response = null;
-                try
-                {
-                    response = await this.httpUpload.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)
-                        .ConfigureAwait(false);
+            HttpResponseMessage response = null;
+            try
+            {
+                response = await this.httpUpload.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)
+                    .ConfigureAwait(false);
 
-                    await this.CheckStatusCode(response)
-                        .ConfigureAwait(false);
+                await this.CheckStatusCode(response)
+                    .ConfigureAwait(false);
 
-                    var result = new LazyJson<T>(response);
-                    response = null;
+                var result = new LazyJson<T>(response);
+                response = null;
 
-                    return result;
-                }
-                catch (HttpRequestException ex)
-                {
-                    throw TwitterApiException.CreateFromException(ex);
-                }
-                catch (OperationCanceledException ex)
-                {
-                    throw TwitterApiException.CreateFromException(ex);
-                }
-                finally
-                {
-                    response?.Dispose();
-                }
+                return result;
+            }
+            catch (HttpRequestException ex)
+            {
+                throw TwitterApiException.CreateFromException(ex);
+            }
+            catch (OperationCanceledException ex)
+            {
+                throw TwitterApiException.CreateFromException(ex);
+            }
+            finally
+            {
+                response?.Dispose();
             }
         }
 
@@ -291,38 +284,35 @@ namespace OpenTween.Connection
             var requestUri = new Uri(RestApiBase, uri);
             var request = new HttpRequestMessage(HttpMethod.Post, requestUri);
 
-            using (var postContent = new MultipartFormDataContent())
+            using var postContent = new MultipartFormDataContent();
+            if (param != null)
             {
-                if (param != null)
-                {
-                    foreach (var (key, value) in param)
-                        postContent.Add(new StringContent(value), key);
-                }
-                if (media != null)
-                {
-                    foreach (var (key, value) in media)
-                        postContent.Add(new StreamContent(value.OpenRead()), key, value.Name);
-                }
+                foreach (var (key, value) in param)
+                    postContent.Add(new StringContent(value), key);
+            }
+            if (media != null)
+            {
+                foreach (var (key, value) in media)
+                    postContent.Add(new StreamContent(value.OpenRead()), key, value.Name);
+            }
 
-                request.Content = postContent;
+            request.Content = postContent;
 
-                try
-                {
-                    using (var response = await this.httpUpload.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)
-                        .ConfigureAwait(false))
-                    {
-                        await this.CheckStatusCode(response)
-                            .ConfigureAwait(false);
-                    }
-                }
-                catch (HttpRequestException ex)
-                {
-                    throw TwitterApiException.CreateFromException(ex);
-                }
-                catch (OperationCanceledException ex)
-                {
-                    throw TwitterApiException.CreateFromException(ex);
-                }
+            try
+            {
+                using var response = await this.httpUpload.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)
+                    .ConfigureAwait(false);
+
+                await this.CheckStatusCode(response)
+                    .ConfigureAwait(false);
+            }
+            catch (HttpRequestException ex)
+            {
+                throw TwitterApiException.CreateFromException(ex);
+            }
+            catch (OperationCanceledException ex)
+            {
+                throw TwitterApiException.CreateFromException(ex);
             }
         }
 
@@ -336,52 +326,49 @@ namespace OpenTween.Connection
             var requestUri = new Uri(RestApiBase, uri);
             var request = new HttpRequestMessage(HttpMethod.Post, requestUri);
 
-            using (var postContent = new StringContent(json, Encoding.UTF8, "application/json"))
-            {
-                request.Content = postContent;
+            using var postContent = new StringContent(json, Encoding.UTF8, "application/json");
+            request.Content = postContent;
 
-                HttpResponseMessage response = null;
-                try
-                {
-                    response = await this.http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)
-                        .ConfigureAwait(false);
+            HttpResponseMessage response = null;
+            try
+            {
+                response = await this.http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)
+                    .ConfigureAwait(false);
 
-                    await this.CheckStatusCode(response)
-                        .ConfigureAwait(false);
+                await this.CheckStatusCode(response)
+                    .ConfigureAwait(false);
 
-                    var result = new LazyJson<T>(response);
-                    response = null;
+                var result = new LazyJson<T>(response);
+                response = null;
 
-                    return result;
-                }
-                catch (HttpRequestException ex)
-                {
-                    throw TwitterApiException.CreateFromException(ex);
-                }
-                catch (OperationCanceledException ex)
-                {
-                    throw TwitterApiException.CreateFromException(ex);
-                }
-                finally
-                {
-                    response?.Dispose();
-                }
+                return result;
+            }
+            catch (HttpRequestException ex)
+            {
+                throw TwitterApiException.CreateFromException(ex);
+            }
+            catch (OperationCanceledException ex)
+            {
+                throw TwitterApiException.CreateFromException(ex);
+            }
+            finally
+            {
+                response?.Dispose();
             }
         }
 
         public async Task DeleteAsync(Uri uri)
         {
             var requestUri = new Uri(RestApiBase, uri);
-            var request = new HttpRequestMessage(HttpMethod.Delete, requestUri);
+            using var request = new HttpRequestMessage(HttpMethod.Delete, requestUri);
 
             try
             {
-                using (var response = await this.http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)
-                    .ConfigureAwait(false))
-                {
-                    await this.CheckStatusCode(response)
-                        .ConfigureAwait(false);
-                }
+                using var response = await this.http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)
+                    .ConfigureAwait(false);
+
+                await this.CheckStatusCode(response)
+                    .ConfigureAwait(false);
             }
             catch (HttpRequestException ex)
             {
@@ -526,22 +513,21 @@ namespace OpenTween.Connection
 
             try
             {
-                using (var request = new HttpRequestMessage(HttpMethod.Post, requestUri))
-                using (var response = await authorizeClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)
-                    .ConfigureAwait(false))
-                using (var content = response.Content)
-                {
-                    var responseText = await content.ReadAsStringAsync()
-                        .ConfigureAwait(false);
+                using var request = new HttpRequestMessage(HttpMethod.Post, requestUri);
+                using var response = await authorizeClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)
+                    .ConfigureAwait(false);
+
+                using var content = response.Content;
+                var responseText = await content.ReadAsStringAsync()
+                    .ConfigureAwait(false);
 
-                    if (!response.IsSuccessStatusCode)
-                        throw new TwitterApiException(response.StatusCode, responseText);
+                if (!response.IsSuccessStatusCode)
+                    throw new TwitterApiException(response.StatusCode, responseText);
 
-                    var responseParams = HttpUtility.ParseQueryString(responseText);
+                var responseParams = HttpUtility.ParseQueryString(responseText);
 
-                    return responseParams.Cast<string>()
-                        .ToDictionary(x => x, x => responseParams[x]);
-                }
+                return responseParams.Cast<string>()
+                    .ToDictionary(x => x, x => responseParams[x]);
             }
             catch (HttpRequestException ex)
             {
index 80e6c53..3240688 100644 (file)
@@ -155,20 +155,18 @@ namespace OpenTween.Connection
                 return mediaId;
             }
 
-            using (var origImage = mediaItem.CreateImage())
+            using var origImage = mediaItem.CreateImage();
+
+            if (SettingManager.Common.AlphaPNGWorkaround && this.AddAlphaChannelIfNeeded(origImage.Image, out var newImage))
             {
-                if (SettingManager.Common.AlphaPNGWorkaround && this.AddAlphaChannelIfNeeded(origImage.Image, out var newImage))
-                {
-                    using (var newMediaItem = new MemoryImageMediaItem(newImage))
-                    {
-                        newMediaItem.AltText = mediaItem.AltText;
-                        return await UploadInternal(newMediaItem, mediaCategory);
-                    }
-                }
-                else
-                {
-                    return await UploadInternal(mediaItem, mediaCategory);
-                }
+                using var newMediaItem = new MemoryImageMediaItem(newImage);
+                newMediaItem.AltText = mediaItem.AltText;
+
+                return await UploadInternal(newMediaItem, mediaCategory);
+            }
+            else
+            {
+                return await UploadInternal(mediaItem, mediaCategory);
             }
         }
 
@@ -189,28 +187,27 @@ namespace OpenTween.Connection
             if (origImage.RawFormat.Guid != ImageFormat.Png.Guid)
                 return false;
 
-            using (var bitmap = new Bitmap(origImage))
+            using var bitmap = new Bitmap(origImage);
+
+            // アルファ値が 255 以外のピクセルが含まれていた場合は何もしない
+            foreach (var x in Enumerable.Range(0, bitmap.Width))
             {
-                // アルファ値が 255 以外のピクセルが含まれていた場合は何もしない
-                foreach (var x in Enumerable.Range(0, bitmap.Width))
+                foreach (var y in Enumerable.Range(0, bitmap.Height))
                 {
-                    foreach (var y in Enumerable.Range(0, bitmap.Height))
-                    {
-                        if (bitmap.GetPixel(x, y).A != 255)
-                            return false;
-                    }
+                    if (bitmap.GetPixel(x, y).A != 255)
+                        return false;
                 }
+            }
 
-                // 左上の 1px だけアルファ値を 254 にする
-                var pixel = bitmap.GetPixel(0, 0);
-                var newPixel = Color.FromArgb(pixel.A - 1, pixel.R, pixel.G, pixel.B);
-                bitmap.SetPixel(0, 0, newPixel);
+            // 左上の 1px だけアルファ値を 254 にする
+            var pixel = bitmap.GetPixel(0, 0);
+            var newPixel = Color.FromArgb(pixel.A - 1, pixel.R, pixel.G, pixel.B);
+            bitmap.SetPixel(0, 0, newPixel);
 
-                // MemoryImage 作成時に画像はコピーされるため、この後 bitmap は破棄しても問題ない
-                newImage = MemoryImage.CopyFromImage(bitmap);
+            // MemoryImage 作成時に画像はコピーされるため、この後 bitmap は破棄しても問題ない
+            newImage = MemoryImage.CopyFromImage(bitmap);
 
-                return true;
-            }
+            return true;
         }
     }
 }
index 439753a..95c01c6 100644 (file)
@@ -261,20 +261,19 @@ namespace OpenTween
             if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
             {
                 if (!SaveFileDialog1.ValidateNames) return;
-                using (var sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
+                using var sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8);
+
+                switch (rslt)
                 {
-                    switch (rslt)
-                    {
-                        case DialogResult.Yes:
-                            SaveEventLog(_filterdEventSource.ToList(), sw);
-                            break;
-                        case DialogResult.No:
-                            SaveEventLog(EventSource, sw);
-                            break;
-                        default:
-                            //
-                            break;
-                    }
+                    case DialogResult.Yes:
+                        SaveEventLog(_filterdEventSource.ToList(), sw);
+                        break;
+                    case DialogResult.No:
+                        SaveEventLog(EventSource, sw);
+                        break;
+                    default:
+                        //
+                        break;
                 }
             }
             this.TopMost = SettingManager.Common.AlwaysTop;
index 76c1ab8..f0a980e 100644 (file)
@@ -147,8 +147,8 @@ namespace OpenTween
         public static async Task ForEachAsync<T>(this IObservable<T> observable, Func<T, Task> subscriber, CancellationToken cancellationToken)
         {
             var observer = new ForEachObserver<T>(subscriber);
+            using var unsubscriber = observable.Subscribe(observer);
 
-            using (var unsubscriber = observable.Subscribe(observer))
             using (cancellationToken.Register(() => unsubscriber.Dispose()))
                 await observer.Task.ConfigureAwait(false);
         }
index c0391a9..48c7941 100644 (file)
@@ -993,27 +993,27 @@ namespace OpenTween
                 {
                     try
                     {
-                        using (var dialog = new WaitingDialog(Properties.Resources.ListsGetting))
-                        {
-                            var cancellationToken = dialog.EnableCancellation();
+                        using var dialog = new WaitingDialog(Properties.Resources.ListsGetting);
+                        var cancellationToken = dialog.EnableCancellation();
 
-                            var task = ((TweenMain)this.Owner).TwitterInstance.GetListsApi();
-                            await dialog.WaitForAsync(this, task);
+                        var task = ((TweenMain)this.Owner).TwitterInstance.GetListsApi();
+                        await dialog.WaitForAsync(this, task);
 
-                            cancellationToken.ThrowIfCancellationRequested();
-                        }
+                        cancellationToken.ThrowIfCancellationRequested();
                     }
                     catch (OperationCanceledException) { return; }
                     catch (WebApiException ex)
                     {
                         MessageBox.Show("Failed to get lists. (" + ex.Message + ")");
                     }
-                    using (var listAvail = new ListAvailable())
-                    {
-                        if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
-                        if (listAvail.SelectedList == null) return;
-                        list = listAvail.SelectedList;
-                    }
+
+                    using var listAvail = new ListAvailable();
+
+                    if (listAvail.ShowDialog(this) == DialogResult.Cancel)
+                        return;
+                    if (listAvail.SelectedList == null)
+                        return;
+                    list = listAvail.SelectedList;
                 }
 
                 TabModel tab;
index 5643a54..b0cd858 100644 (file)
@@ -95,22 +95,16 @@ namespace OpenTween
 
         private byte[] IconToByteArray(string filename)
         {
-            using (var ic = new Icon(filename))
-            {
-                return IconToByteArray(ic);
-            }
+            using var ic = new Icon(filename);
+            return IconToByteArray(ic);
         }
 
         private byte[] IconToByteArray(Icon icondata)
         {
-            using (var ms = new MemoryStream())
-            {
-                using (var ic = new Icon(icondata, 48, 48))
-                {
-                    ic.ToBitmap().Save(ms, ImageFormat.Png);
-                    return ms.ToArray();
-                }
-            }
+            using var ms = new MemoryStream();
+            using var ic = new Icon(icondata, 48, 48);
+            ic.ToBitmap().Save(ms, ImageFormat.Png);
+            return ms.ToArray();
         }
 
         public static bool IsDllExists
index 846170b..6e2d348 100644 (file)
@@ -115,16 +115,16 @@ namespace OpenTween
 
         private async Task<MemoryImage> FetchImageAsync(string uri, CancellationToken cancelToken)
         {
-            using (var response = await Networking.Http.GetAsync(uri, cancelToken).ConfigureAwait(false))
-            {
-                response.EnsureSuccessStatusCode();
+            using var response = await Networking.Http.GetAsync(uri, cancelToken)
+                .ConfigureAwait(false);
 
-                using (var imageStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
-                {
-                    return await MemoryImage.CopyFromStreamAsync(imageStream)
-                        .ConfigureAwait(false);
-                }
-            }
+            response.EnsureSuccessStatusCode();
+
+            using var imageStream = await response.Content.ReadAsStreamAsync()
+                .ConfigureAwait(false);
+
+            return await MemoryImage.CopyFromStreamAsync(imageStream)
+                .ConfigureAwait(false);
         }
 
         public MemoryImage TryGetFromCache(string address)
index c47253a..4e5839f 100644 (file)
@@ -52,16 +52,14 @@ namespace OpenTween
 
         public static DialogResult Show(IWin32Window owner, string text, string caption, out string inputText)
         {
-            using (var dialog = new InputDialog())
-            {
-                dialog.labelMain.Text = text;
-                dialog.Text = caption;
+            using var dialog = new InputDialog();
+            dialog.labelMain.Text = text;
+            dialog.Text = caption;
 
-                var result = dialog.ShowDialog(owner);
-                inputText = dialog.textBox.Text;
+            var result = dialog.ShowDialog(owner);
+            inputText = dialog.textBox.Text;
 
-                return result;
-            }
+            return result;
         }
     }
 }
index f1a8407..6df7500 100644 (file)
@@ -141,16 +141,14 @@ namespace OpenTween
 
         private async Task<IReadOnlyList<ListElement>> FetchListsAsync()
         {
-            using (var dialog = new WaitingDialog("Getting Lists..."))
-            {
-                var cancellationToken = dialog.EnableCancellation();
+            using var dialog = new WaitingDialog("Getting Lists...");
+            var cancellationToken = dialog.EnableCancellation();
 
-                var tw = ((TweenMain)this.Owner).TwitterInstance;
-                var task = tw.GetListsApi();
-                await dialog.WaitForAsync(this, task);
+            var tw = ((TweenMain)this.Owner).TwitterInstance;
+            var task = tw.GetListsApi();
+            await dialog.WaitForAsync(this, task);
 
-                cancellationToken.ThrowIfCancellationRequested();
-            }
+            cancellationToken.ThrowIfCancellationRequested();
 
             return TabInformations.GetInstance().SubscribableLists;
         }
index 7ada81c..55c6cb5 100644 (file)
@@ -346,20 +346,18 @@ namespace OpenTween
             {
                 var uri = imageUri.AbsoluteUri.Replace("_normal", "_bigger");
 
-                using (var imageStream = await Networking.Http.GetStreamAsync(uri))
-                {
-                    var image = await MemoryImage.CopyFromStreamAsync(imageStream);
-
-                    // 画像の読み込み中に選択中のユーザーが変化していたらキャンセルとして扱う
-                    var selectedUser = (UserInfo)this.UserList.SelectedItem;
-                    if (selectedUser.Id != userId)
-                    {
-                        image.Dispose();
-                        throw new OperationCanceledException();
-                    }
+                using var imageStream = await Networking.Http.GetStreamAsync(uri);
+                var image = await MemoryImage.CopyFromStreamAsync(imageStream);
 
-                    return image;
+                // 画像の読み込み中に選択中のユーザーが変化していたらキャンセルとして扱う
+                var selectedUser = (UserInfo)this.UserList.SelectedItem;
+                if (selectedUser.Id != userId)
+                {
+                    image.Dispose();
+                    throw new OperationCanceledException();
                 }
+
+                return image;
             });
         }
 
@@ -382,15 +380,13 @@ namespace OpenTween
 
         private async Task<IReadOnlyList<ListElement>> FetchListsAsync()
         {
-            using (var dialog = new WaitingDialog(Properties.Resources.ListsGetting))
-            {
-                var cancellationToken = dialog.EnableCancellation();
+            using var dialog = new WaitingDialog(Properties.Resources.ListsGetting);
+            var cancellationToken = dialog.EnableCancellation();
 
-                var task = this.tw.GetListsApi();
-                await dialog.WaitForAsync(this, task);
+            var task = this.tw.GetListsApi();
+            await dialog.WaitForAsync(this, task);
 
-                cancellationToken.ThrowIfCancellationRequested();
-            }
+            cancellationToken.ThrowIfCancellationRequested();
 
             return TabInformations.GetInstance().SubscribableLists;
         }
index 26dff95..6fd1e46 100644 (file)
@@ -145,10 +145,8 @@ namespace OpenTween
 
         public MemoryImage CreateImage()
         {
-            using (var fs = this.FileInfo.OpenRead())
-            {
-                return MemoryImage.CopyFromStream(fs);
-            }
+            using var fs = this.FileInfo.OpenRead();
+            return MemoryImage.CopyFromStream(fs);
         }
 
         public Stream OpenRead()
@@ -156,10 +154,8 @@ namespace OpenTween
 
         public void CopyTo(Stream stream)
         {
-            using (var fs = this.FileInfo.OpenRead())
-            {
-                fs.CopyTo(stream);
-            }
+            using var fs = this.FileInfo.OpenRead();
+            fs.CopyTo(stream);
         }
     }
 
index 10d37c1..d7f3f09 100644 (file)
@@ -176,11 +176,9 @@ namespace OpenTween
 
         public override int GetHashCode()
         {
-            using (var sha1service = new System.Security.Cryptography.SHA1CryptoServiceProvider())
-            {
-                var hash = sha1service.ComputeHash(this.Stream.GetBuffer(), 0, (int)this.Stream.Length);
-                return Convert.ToBase64String(hash).GetHashCode();
-            }
+            using var sha1service = new System.Security.Cryptography.SHA1CryptoServiceProvider();
+            var hash = sha1service.ComputeHash(this.Stream.GetBuffer(), 0, (int)this.Stream.Length);
+            return Convert.ToBase64String(hash).GetHashCode();
         }
 
         public override bool Equals(object other)
index 32eda4c..ce83e65 100644 (file)
@@ -276,19 +276,18 @@ namespace OpenTween
                 var fileName = $"{ApplicationSettings.AssemblyName}Trace-{now.ToLocalTime():yyyyMMdd-HHmmss}.log";
                 fileName = Path.Combine(logPath, fileName);
 
-                using (var writer = new StreamWriter(fileName))
-                {
-                    writer.WriteLine("**** TraceOut: {0} ****", now.ToLocalTimeString());
-                    writer.WriteLine(Properties.Resources.TraceOutText1, ApplicationSettings.FeedbackEmailAddress);
-                    writer.WriteLine(Properties.Resources.TraceOutText2, ApplicationSettings.FeedbackTwitterName);
-                    writer.WriteLine();
-                    writer.WriteLine(Properties.Resources.TraceOutText3);
-                    writer.WriteLine(Properties.Resources.TraceOutText4, Environment.OSVersion.VersionString);
-                    writer.WriteLine(Properties.Resources.TraceOutText5, Environment.Version);
-                    writer.WriteLine(Properties.Resources.TraceOutText6, ApplicationSettings.AssemblyName, FileVersion);
-                    writer.WriteLine(Message);
-                    writer.WriteLine();
-                }
+                using var writer = new StreamWriter(fileName);
+
+                writer.WriteLine("**** TraceOut: {0} ****", now.ToLocalTimeString());
+                writer.WriteLine(Properties.Resources.TraceOutText1, ApplicationSettings.FeedbackEmailAddress);
+                writer.WriteLine(Properties.Resources.TraceOutText2, ApplicationSettings.FeedbackTwitterName);
+                writer.WriteLine();
+                writer.WriteLine(Properties.Resources.TraceOutText3);
+                writer.WriteLine(Properties.Resources.TraceOutText4, Environment.OSVersion.VersionString);
+                writer.WriteLine(Properties.Resources.TraceOutText5, Environment.Version);
+                writer.WriteLine(Properties.Resources.TraceOutText6, ApplicationSettings.AssemblyName, FileVersion);
+                writer.WriteLine(Message);
+                writer.WriteLine();
             }
         }
 
@@ -445,11 +444,9 @@ namespace OpenTween
                 return;
             }
 
-            using (var dialog = new SendErrorReportForm())
-            {
-                dialog.ErrorReport = report;
-                dialog.ShowDialog(owner);
-            }
+            using var dialog = new SendErrorReportForm();
+            dialog.ErrorReport = report;
+            dialog.ShowDialog(owner);
         }
 
         /// <summary>
@@ -553,49 +550,47 @@ namespace OpenTween
             var bytesIn = Encoding.UTF8.GetBytes(str);
 
             //DESCryptoServiceProviderオブジェクトの作成
-            using (var des = new DESCryptoServiceProvider())
+            using var des = new DESCryptoServiceProvider();
+
+            //共有キーと初期化ベクタを決定
+            //パスワードをバイト配列にする
+            var bytesKey = Encoding.UTF8.GetBytes("_tween_encrypt_key_");
+            //共有キーと初期化ベクタを設定
+            des.Key = ResizeBytesArray(bytesKey, des.Key.Length);
+            des.IV = ResizeBytesArray(bytesKey, des.IV.Length);
+
+            MemoryStream msOut = null;
+            ICryptoTransform desdecrypt = null;
+
+            try
             {
-                //共有キーと初期化ベクタを決定
-                //パスワードをバイト配列にする
-                var bytesKey = Encoding.UTF8.GetBytes("_tween_encrypt_key_");
-                //共有キーと初期化ベクタを設定
-                des.Key = ResizeBytesArray(bytesKey, des.Key.Length);
-                des.IV = ResizeBytesArray(bytesKey, des.IV.Length);
+                //暗号化されたデータを書き出すためのMemoryStream
+                msOut = new MemoryStream();
 
-                MemoryStream msOut = null;
-                ICryptoTransform desdecrypt = null;
+                //DES暗号化オブジェクトの作成
+                desdecrypt = des.CreateEncryptor();
 
-                try
-                {
-                    //暗号化されたデータを書き出すためのMemoryStream
-                    msOut = new MemoryStream();
+                //書き込むためのCryptoStreamの作成
+                using var cryptStream = new CryptoStream(msOut, desdecrypt, CryptoStreamMode.Write);
 
-                    //DES暗号化オブジェクトの作成
-                    desdecrypt = des.CreateEncryptor();
+                //Disposeが重複して呼ばれないようにする
+                var msTmp = msOut;
+                msOut = null;
+                desdecrypt = null;
 
-                    //書き込むためのCryptoStreamの作成
-                    using (var cryptStream = new CryptoStream(msOut, desdecrypt, CryptoStreamMode.Write))
-                    {
-                        //Disposeが重複して呼ばれないようにする
-                        var msTmp = msOut;
-                        msOut = null;
-                        desdecrypt = null;
-
-                        //書き込む
-                        cryptStream.Write(bytesIn, 0, bytesIn.Length);
-                        cryptStream.FlushFinalBlock();
-                        //暗号化されたデータを取得
-                        var bytesOut = msTmp.ToArray();
-
-                        //Base64で文字列に変更して結果を返す
-                        return Convert.ToBase64String(bytesOut);
-                    }
-                }
-                finally
-                {
-                    msOut?.Dispose();
-                    desdecrypt?.Dispose();
-                }
+                //書き込む
+                cryptStream.Write(bytesIn, 0, bytesIn.Length);
+                cryptStream.FlushFinalBlock();
+                //暗号化されたデータを取得
+                var bytesOut = msTmp.ToArray();
+
+                //Base64で文字列に変更して結果を返す
+                return Convert.ToBase64String(bytesOut);
+            }
+            finally
+            {
+                msOut?.Dispose();
+                desdecrypt?.Dispose();
             }
         }
 
@@ -604,53 +599,51 @@ namespace OpenTween
             if (string.IsNullOrEmpty(str)) return "";
 
             //DESCryptoServiceProviderオブジェクトの作成
-            using (var des = new System.Security.Cryptography.DESCryptoServiceProvider())
+            using var des = new DESCryptoServiceProvider();
+
+            //共有キーと初期化ベクタを決定
+            //パスワードをバイト配列にする
+            var bytesKey = Encoding.UTF8.GetBytes("_tween_encrypt_key_");
+            //共有キーと初期化ベクタを設定
+            des.Key = ResizeBytesArray(bytesKey, des.Key.Length);
+            des.IV = ResizeBytesArray(bytesKey, des.IV.Length);
+
+            //Base64で文字列をバイト配列に戻す
+            var bytesIn = Convert.FromBase64String(str);
+
+            MemoryStream msIn = null;
+            ICryptoTransform desdecrypt = null;
+            CryptoStream cryptStreem = null;
+
+            try
             {
-                //共有キーと初期化ベクタを決定
-                //パスワードをバイト配列にする
-                var bytesKey = Encoding.UTF8.GetBytes("_tween_encrypt_key_");
-                //共有キーと初期化ベクタを設定
-                des.Key = ResizeBytesArray(bytesKey, des.Key.Length);
-                des.IV = ResizeBytesArray(bytesKey, des.IV.Length);
+                //暗号化されたデータを読み込むためのMemoryStream
+                msIn = new MemoryStream(bytesIn);
+                //DES復号化オブジェクトの作成
+                desdecrypt = des.CreateDecryptor();
+                //読み込むためのCryptoStreamの作成
+                cryptStreem = new CryptoStream(msIn, desdecrypt, CryptoStreamMode.Read);
 
-                //Base64で文字列をバイト配列に戻す
-                var bytesIn = Convert.FromBase64String(str);
+                //Disposeが重複して呼ばれないようにする
+                msIn = null;
+                desdecrypt = null;
 
-                MemoryStream msIn = null;
-                ICryptoTransform desdecrypt = null;
-                CryptoStream cryptStreem = null;
+                //復号化されたデータを取得するためのStreamReader
+                using var srOut = new StreamReader(cryptStreem, Encoding.UTF8);
 
-                try
-                {
-                    //暗号化されたデータを読み込むためのMemoryStream
-                    msIn = new MemoryStream(bytesIn);
-                    //DES復号化オブジェクトの作成
-                    desdecrypt = des.CreateDecryptor();
-                    //読み込むためのCryptoStreamの作成
-                    cryptStreem = new CryptoStream(msIn, desdecrypt, CryptoStreamMode.Read);
-
-                    //Disposeが重複して呼ばれないようにする
-                    msIn = null;
-                    desdecrypt = null;
-
-                    //復号化されたデータを取得するためのStreamReader
-                    using (var srOut = new StreamReader(cryptStreem, Encoding.UTF8))
-                    {
-                        //Disposeが重複して呼ばれないようにする
-                        cryptStreem = null;
+                //Disposeが重複して呼ばれないようにする
+                cryptStreem = null;
 
-                        //復号化されたデータを取得する
-                        var result = srOut.ReadToEnd();
+                //復号化されたデータを取得する
+                var result = srOut.ReadToEnd();
 
-                        return result;
-                    }
-                }
-                finally
-                {
-                    msIn?.Dispose();
-                    desdecrypt?.Dispose();
-                    cryptStreem?.Dispose();
-                }
+                return result;
+            }
+            finally
+            {
+                msIn?.Dispose();
+                desdecrypt?.Dispose();
+                cryptStreem?.Dispose();
             }
         }
 
@@ -754,17 +747,13 @@ namespace OpenTween
 
         public static T CreateDataFromJson<T>(string content)
         {
-            T data;
             var buf = Encoding.Unicode.GetBytes(content);
-            using (var stream = new MemoryStream(buf))
+            using var stream = new MemoryStream(buf);
+            var settings = new DataContractJsonSerializerSettings
             {
-                var settings = new DataContractJsonSerializerSettings
-                {
-                    UseSimpleDictionaryFormat = true,
-                };
-                data = (T)((new DataContractJsonSerializer(typeof(T), settings)).ReadObject(stream));
-            }
-            return data;
+                UseSimpleDictionaryFormat = true,
+            };
+            return (T)((new DataContractJsonSerializer(typeof(T), settings)).ReadObject(stream));
         }
 
         public static bool IsNetworkAvailable()
index 08f6d5f..7762554 100644 (file)
@@ -102,17 +102,16 @@ namespace OpenTween.Setting.Panel
 
         private void Button3_Click(object sender, EventArgs e)
         {
-            using (var filedlg = new OpenFileDialog())
-            {
-                filedlg.Filter = Properties.Resources.Button3_ClickText1;
-                filedlg.FilterIndex = 1;
-                filedlg.Title = Properties.Resources.Button3_ClickText2;
-                filedlg.RestoreDirectory = true;
+            using var filedlg = new OpenFileDialog();
+
+            filedlg.Filter = Properties.Resources.Button3_ClickText1;
+            filedlg.FilterIndex = 1;
+            filedlg.Title = Properties.Resources.Button3_ClickText2;
+            filedlg.RestoreDirectory = true;
 
-                if (filedlg.ShowDialog() == DialogResult.OK)
-                {
-                    BrowserPathText.Text = filedlg.FileName;
-                }
+            if (filedlg.ShowDialog() == DialogResult.OK)
+            {
+                BrowserPathText.Text = filedlg.FileName;
             }
         }
 
index 5174f74..ae542d2 100644 (file)
@@ -88,32 +88,31 @@ namespace OpenTween.Setting.Panel
 
         private void ButtonBitlyAuthorize_Click(object sender, EventArgs e)
         {
-            using (var dialog = new LoginDialog())
-            {
-                const string DialogText = "Bitly Login";
-                dialog.Text = DialogText;
+            using var dialog = new LoginDialog();
 
-                string accessToken = null;
-                dialog.LoginCallback = async () =>
-                {
-                    try
-                    {
-                        var bitly = new BitlyApi();
-                        accessToken = await bitly.GetAccessTokenAsync(dialog.LoginName, dialog.Password);
-                        return true;
-                    }
-                    catch (WebApiException ex)
-                    {
-                        var text = string.Format(Properties.Resources.BitlyAuthorize_ErrorText, ex.Message);
-                        MessageBox.Show(dialog, text, DialogText, MessageBoxButtons.OK, MessageBoxIcon.Error);
-                        return false;
-                    }
-                };
+            const string DialogText = "Bitly Login";
+            dialog.Text = DialogText;
 
-                if (dialog.ShowDialog(this.ParentForm) == DialogResult.OK)
+            string accessToken = null;
+            dialog.LoginCallback = async () =>
+            {
+                try
                 {
-                    this.TextBitlyAccessToken.Text = accessToken;
+                    var bitly = new BitlyApi();
+                    accessToken = await bitly.GetAccessTokenAsync(dialog.LoginName, dialog.Password);
+                    return true;
                 }
+                catch (WebApiException ex)
+                {
+                    var text = string.Format(Properties.Resources.BitlyAuthorize_ErrorText, ex.Message);
+                    MessageBox.Show(dialog, text, DialogText, MessageBoxButtons.OK, MessageBoxIcon.Error);
+                    return false;
+                }
+            };
+
+            if (dialog.ShowDialog(this.ParentForm) == DialogResult.OK)
+            {
+                this.TextBitlyAccessToken.Text = accessToken;
             }
         }
     }
index eec20de..9321ea0 100644 (file)
@@ -62,13 +62,11 @@ namespace OpenTween
 
                 lock (lockObj)
                 {
-                    using (var fs = new FileStream(settingFilePath, FileMode.Open, FileAccess.Read))
-                    {
-                        fs.Position = 0;
-                        var xs = new XmlSerializer(typeof(T));
-                        var instance = (T)xs.Deserialize(fs);
-                        return instance;
-                    }
+                    using var fs = new FileStream(settingFilePath, FileMode.Open, FileAccess.Read);
+                    fs.Position = 0;
+                    var xs = new XmlSerializer(typeof(T));
+                    var instance = (T)xs.Deserialize(fs);
+                    return instance;
                 }
             }
             catch (FileNotFoundException)
@@ -88,14 +86,12 @@ namespace OpenTween
                     {
                         lock (lockObj)
                         {
-                            using (var fs = new FileStream(backupFile, FileMode.Open, FileAccess.Read))
-                            {
-                                fs.Position = 0;
-                                var xs = new XmlSerializer(typeof(T));
-                                var instance = (T)xs.Deserialize(fs);
-                                MessageBox.Show("File: " + GetSettingFilePath(FileId) + Environment.NewLine + "Use old setting file, because application can't read this setting file.");
-                                return instance;
-                            }
+                            using var fs = new FileStream(backupFile, FileMode.Open, FileAccess.Read);
+                            fs.Position = 0;
+                            var xs = new XmlSerializer(typeof(T));
+                            var instance = (T)xs.Deserialize(fs);
+                            MessageBox.Show("File: " + GetSettingFilePath(FileId) + Environment.NewLine + "Use old setting file, because application can't read this setting file.");
+                            return instance;
                         }
                     }
                     catch (Exception)
index 8230665..cc218e0 100644 (file)
@@ -358,18 +358,18 @@ namespace OpenTween
                 new KeyValuePair<string, string>("url", srcUri.OriginalString),
             });
 
-            using (var response = await this.http.PostAsync("https://tinyurl.com/api-create.php", content).ConfigureAwait(false))
-            {
-                response.EnsureSuccessStatusCode();
+            using var response = await this.http.PostAsync("https://tinyurl.com/api-create.php", content)
+                .ConfigureAwait(false);
 
-                var result = await response.Content.ReadAsStringAsync()
-                    .ConfigureAwait(false);
+            response.EnsureSuccessStatusCode();
 
-                if (!Regex.IsMatch(result, @"^https?://"))
-                    throw new WebApiException("Failed to create URL.", result);
+            var result = await response.Content.ReadAsStringAsync()
+                .ConfigureAwait(false);
 
-                return this.UpgradeToHttpsIfAvailable(new Uri(result.TrimEnd()));
-            }
+            if (!Regex.IsMatch(result, @"^https?://"))
+                throw new WebApiException("Failed to create URL.", result);
+
+            return this.UpgradeToHttpsIfAvailable(new Uri(result.TrimEnd()));
         }
 
         private async Task<Uri> ShortenByIsgdAsync(Uri srcUri)
@@ -384,18 +384,18 @@ namespace OpenTween
                 new KeyValuePair<string, string>("url", srcUri.OriginalString),
             });
 
-            using (var response = await this.http.PostAsync("https://is.gd/create.php", content).ConfigureAwait(false))
-            {
-                response.EnsureSuccessStatusCode();
+            using var response = await this.http.PostAsync("https://is.gd/create.php", content)
+                .ConfigureAwait(false);
 
-                var result = await response.Content.ReadAsStringAsync()
-                    .ConfigureAwait(false);
+            response.EnsureSuccessStatusCode();
+
+            var result = await response.Content.ReadAsStringAsync()
+                .ConfigureAwait(false);
 
-                if (!Regex.IsMatch(result, @"^https?://"))
-                    throw new WebApiException("Failed to create URL.", result);
+            if (!Regex.IsMatch(result, @"^https?://"))
+                throw new WebApiException("Failed to create URL.", result);
 
-                return new Uri(result.TrimEnd());
-            }
+            return new Uri(result.TrimEnd());
         }
 
         private async Task<Uri> ShortenByBitlyAsync(Uri srcUri, string domain = "bit.ly")
@@ -434,18 +434,18 @@ namespace OpenTween
             };
 
             var uri = new Uri("https://ux.nu/api/short?" + MyCommon.BuildQueryString(query));
-            using (var response = await this.http.GetAsync(uri).ConfigureAwait(false))
-            {
-                response.EnsureSuccessStatusCode();
+            using var response = await this.http.GetAsync(uri)
+                .ConfigureAwait(false);
 
-                var result = await response.Content.ReadAsStringAsync()
-                    .ConfigureAwait(false);
+            response.EnsureSuccessStatusCode();
+
+            var result = await response.Content.ReadAsStringAsync()
+                .ConfigureAwait(false);
 
-                if (!Regex.IsMatch(result, @"^https?://"))
-                    throw new WebApiException("Failed to create URL.", result);
+            if (!Regex.IsMatch(result, @"^https?://"))
+                throw new WebApiException("Failed to create URL.", result);
 
-                return new Uri(result.TrimEnd());
-            }
+            return new Uri(result.TrimEnd());
         }
 
         private bool IsIrregularShortUrl(Uri uri)
@@ -465,31 +465,31 @@ namespace OpenTween
 
             var request = new HttpRequestMessage(HttpMethod.Head, url);
 
-            using (var response = await this.http.SendAsync(request).ConfigureAwait(false))
+            using var response = await this.http.SendAsync(request)
+                .ConfigureAwait(false);
+
+            if (!response.IsSuccessStatusCode)
             {
-                if (!response.IsSuccessStatusCode)
-                {
-                    // ステータスコードが 3xx であれば例外を発生させない
-                    if ((int)response.StatusCode / 100 != 3)
-                        response.EnsureSuccessStatusCode();
-                }
+                // ステータスコードが 3xx であれば例外を発生させない
+                if ((int)response.StatusCode / 100 != 3)
+                    response.EnsureSuccessStatusCode();
+            }
 
-                var redirectedUrl = response.Headers.Location;
+            var redirectedUrl = response.Headers.Location;
 
-                if (redirectedUrl == null)
-                    return null;
+            if (redirectedUrl == null)
+                return null;
 
-                // サーバーが URL を適切にエンコードしていない場合、OriginalString に非 ASCII 文字が含まれる。
-                // その場合、redirectedUrl は文字化けしている可能性があるため使用しない
-                // 参照: http://stackoverflow.com/questions/1888933
-                if (redirectedUrl.OriginalString.Any(x => x < ' ' || x > '~'))
-                    return null;
+            // サーバーが URL を適切にエンコードしていない場合、OriginalString に非 ASCII 文字が含まれる。
+            // その場合、redirectedUrl は文字化けしている可能性があるため使用しない
+            // 参照: http://stackoverflow.com/questions/1888933
+            if (redirectedUrl.OriginalString.Any(x => x < ' ' || x > '~'))
+                return null;
 
-                if (redirectedUrl.IsAbsoluteUri)
-                    return redirectedUrl;
-                else
-                    return new Uri(url, redirectedUrl);
-            }
+            if (redirectedUrl.IsAbsoluteUri)
+                return redirectedUrl;
+            else
+                return new Uri(url, redirectedUrl);
         }
 
         /// <summary>
index 7e12669..044b2e1 100644 (file)
@@ -119,32 +119,29 @@ namespace OpenTween.Thumbnail
             await Task.WhenAll(tilesTask.Cast<Task<MemoryImage>>())
                 .ConfigureAwait(false);
 
-            using (var bitmap = new Bitmap(this.ThumbnailSize.Width, this.ThumbnailSize.Height))
+            using var bitmap = new Bitmap(this.ThumbnailSize.Width, this.ThumbnailSize.Height);
+
+            using (var g = Graphics.FromImage(bitmap))
             {
-                using (var g = Graphics.FromImage(bitmap))
-                {
-                    g.TranslateTransform(tileOffset.Width, tileOffset.Height);
+                g.TranslateTransform(tileOffset.Width, tileOffset.Height);
 
-                    foreach (var x in Enumerable.Range(0, tileCountX))
+                foreach (var x in Enumerable.Range(0, tileCountX))
+                {
+                    foreach (var y in Enumerable.Range(0, tileCountY))
                     {
-                        foreach (var y in Enumerable.Range(0, tileCountY))
-                        {
-                            using (var image = tilesTask[x, y].Result)
-                            {
-                                g.DrawImage(image.Image, TileSize.Width * x, TileSize.Height * y);
-                            }
-                        }
+                        using var image = tilesTask[x, y].Result;
+                        g.DrawImage(image.Image, TileSize.Width * x, TileSize.Height * y);
                     }
                 }
+            }
 
-                MemoryImage result = null;
-                try
-                {
-                    result = MemoryImage.CopyFromImage(bitmap);
-                    return result;
-                }
-                catch { result?.Dispose(); throw; }
+            MemoryImage result = null;
+            try
+            {
+                result = MemoryImage.CopyFromImage(bitmap);
+                return result;
             }
+            catch { result?.Dispose(); throw; }
         }
 
         /// <summary>指定されたタイル番号のタイル画像を読み込むメソッド</summary>
@@ -152,16 +149,16 @@ namespace OpenTween.Thumbnail
         {
             var tileUrl = TileServerBase + $"/{this.Zoom}/{pos.X}/{pos.Y}.png";
 
-            using (var stream = await http.GetStreamAsync(tileUrl).ConfigureAwait(false))
+            using var stream = await http.GetStreamAsync(tileUrl)
+                .ConfigureAwait(false);
+
+            MemoryImage result = null;
+            try
             {
-                MemoryImage result = null;
-                try
-                {
-                    result = await MemoryImage.CopyFromStreamAsync(stream).ConfigureAwait(false);
-                    return result;
-                }
-                catch { result?.Dispose(); throw; }
+                result = await MemoryImage.CopyFromStreamAsync(stream).ConfigureAwait(false);
+                return result;
             }
+            catch { result?.Dispose(); throw; }
         }
 
         /// <summary>経度・緯度からタイル番号を算出するメソッド</summary>
index 8bfa2a0..d6827d5 100644 (file)
@@ -112,15 +112,15 @@ namespace OpenTween.Thumbnail.Services
 
                 var apiUrl = new Uri(ApiBase + "/checkins/resolve?" + MyCommon.BuildQueryString(query));
 
-                using (var response = await this.http.GetAsync(apiUrl, token).ConfigureAwait(false))
-                {
-                    response.EnsureSuccessStatusCode();
+                using var response = await this.http.GetAsync(apiUrl, token)
+                    .ConfigureAwait(false);
 
-                    var jsonBytes = await response.Content.ReadAsByteArrayAsync()
-                        .ConfigureAwait(false);
+                response.EnsureSuccessStatusCode();
+
+                var jsonBytes = await response.Content.ReadAsByteArrayAsync()
+                    .ConfigureAwait(false);
 
-                    return ParseIntoLocation(jsonBytes);
-                }
+                return ParseIntoLocation(jsonBytes);
             }
             catch (HttpRequestException)
             {
@@ -158,15 +158,15 @@ namespace OpenTween.Thumbnail.Services
 
                 var apiUrl = new Uri(ApiBase + "/checkins/" + checkinIdGroup.Value + "?" + MyCommon.BuildQueryString(query));
 
-                using (var response = await this.http.GetAsync(apiUrl, token).ConfigureAwait(false))
-                {
-                    response.EnsureSuccessStatusCode();
+                using var response = await this.http.GetAsync(apiUrl, token)
+                    .ConfigureAwait(false);
 
-                    var jsonBytes = await response.Content.ReadAsByteArrayAsync()
-                        .ConfigureAwait(false);
+                response.EnsureSuccessStatusCode();
+
+                var jsonBytes = await response.Content.ReadAsByteArrayAsync()
+                    .ConfigureAwait(false);
 
-                    return ParseIntoLocation(jsonBytes);
-                }
+                return ParseIntoLocation(jsonBytes);
             }
             catch (HttpRequestException)
             {
@@ -176,27 +176,25 @@ namespace OpenTween.Thumbnail.Services
 
         internal static GlobalLocation ParseIntoLocation(byte[] jsonBytes)
         {
-            using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(jsonBytes, XmlDictionaryReaderQuotas.Max))
-            {
-                var xElm = XElement.Load(jsonReader);
+            using var jsonReader = JsonReaderWriterFactory.CreateJsonReader(jsonBytes, XmlDictionaryReaderQuotas.Max);
+            var xElm = XElement.Load(jsonReader);
 
-                var locationElm = xElm.XPathSelectElement("/response/checkin/venue/location");
+            var locationElm = xElm.XPathSelectElement("/response/checkin/venue/location");
 
-                // 座標が得られなかった場合
-                if (locationElm == null)
-                    return null;
+            // 座標が得られなかった場合
+            if (locationElm == null)
+                return null;
 
-                // 月など、地球以外の星の座標である場合
-                var planetElm = locationElm.Element("planet");
-                if (planetElm != null && planetElm.Value != "earth")
-                    return null;
+            // 月など、地球以外の星の座標である場合
+            var planetElm = locationElm.Element("planet");
+            if (planetElm != null && planetElm.Value != "earth")
+                return null;
 
-                return new GlobalLocation
-                {
-                    Latitude = double.Parse(locationElm.Element("lat").Value, CultureInfo.InvariantCulture),
-                    Longitude = double.Parse(locationElm.Element("lng").Value, CultureInfo.InvariantCulture),
-                };
-            }
+            return new GlobalLocation
+            {
+                Latitude = double.Parse(locationElm.Element("lat").Value, CultureInfo.InvariantCulture),
+                Longitude = double.Parse(locationElm.Element("lng").Value, CultureInfo.InvariantCulture),
+            };
         }
     }
 }
index 34d37db..89f2bde 100644 (file)
@@ -146,22 +146,20 @@ namespace OpenTween.Thumbnail.Services
                 var jsonBytes = await this.FetchRegexAsync(apiBase)
                     .ConfigureAwait(false);
 
-                using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(jsonBytes, XmlDictionaryReaderQuotas.Max))
-                {
-                    var xElm = XElement.Load(jsonReader);
+                using var jsonReader = JsonReaderWriterFactory.CreateJsonReader(jsonBytes, XmlDictionaryReaderQuotas.Max);
+                var xElm = XElement.Load(jsonReader);
 
-                    if (xElm.Element("error") != null)
-                        return false;
+                if (xElm.Element("error") != null)
+                    return false;
 
-                    lock (this.LockObj)
-                    {
-                        this.UrlRegex = xElm.Elements("item")
-                            .Where(x => !this.ExcludedServiceNames.Contains(x.Element("name").Value))
-                            .Select(e => new Regex(e.Element("regex").Value, RegexOptions.IgnoreCase))
-                            .ToArray();
+                lock (this.LockObj)
+                {
+                    this.UrlRegex = xElm.Elements("item")
+                        .Where(x => !this.ExcludedServiceNames.Contains(x.Element("name").Value))
+                        .Select(e => new Regex(e.Element("regex").Value, RegexOptions.IgnoreCase))
+                        .ToArray();
 
-                        this.ApiBase = apiBase;
-                    }
+                    this.ApiBase = apiBase;
                 }
 
                 return true;
@@ -175,15 +173,14 @@ namespace OpenTween.Thumbnail.Services
 
         protected virtual async Task<byte[]> FetchRegexAsync(string apiBase)
         {
-            using (var cts = new CancellationTokenSource(millisecondsDelay: 1000))
-            using (var response = await this.http.GetAsync(apiBase + "regex.json", cts.Token)
-                .ConfigureAwait(false))
-            {
-                response.EnsureSuccessStatusCode();
+            using var cts = new CancellationTokenSource(millisecondsDelay: 1000);
+            using var response = await this.http.GetAsync(apiBase + "regex.json", cts.Token)
+                .ConfigureAwait(false);
 
-                return await response.Content.ReadAsByteArrayAsync()
-                    .ConfigureAwait(false);
-            }
+            response.EnsureSuccessStatusCode();
+
+            return await response.Content.ReadAsByteArrayAsync()
+                .ConfigureAwait(false);
         }
 
         public override Task<ThumbnailInfo> GetThumbnailInfoAsync(string url, PostClass post, CancellationToken token)
index 572c730..a740f69 100644 (file)
@@ -121,13 +121,13 @@ namespace OpenTween.Thumbnail.Services
 
         protected virtual async Task<string> FetchImageUrlAsync(string url, CancellationToken token)
         {
-            using (var response = await this.http.GetAsync(url, token).ConfigureAwait(false))
-            {
-                response.EnsureSuccessStatusCode();
+            using var response = await this.http.GetAsync(url, token)
+                .ConfigureAwait(false);
 
-                return await response.Content.ReadAsStringAsync()
-                    .ConfigureAwait(false);
-            }
+            response.EnsureSuccessStatusCode();
+
+            return await response.Content.ReadAsStringAsync()
+                .ConfigureAwait(false);
         }
     }
 }
index eb3df51..ab2bf18 100644 (file)
@@ -73,16 +73,16 @@ namespace OpenTween.Thumbnail.Services
                 request.Headers.Add("User-Agent", Networking.GetUserAgentString(fakeMSIE: true));
                 request.Headers.Referrer = new Uri(this.MediaPageUrl);
 
-                using (var response = await http.SendAsync(request, cancellationToken).ConfigureAwait(false))
-                {
-                    response.EnsureSuccessStatusCode();
+                using var response = await http.SendAsync(request, cancellationToken)
+                    .ConfigureAwait(false);
 
-                    using (var imageStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
-                    {
-                        return await MemoryImage.CopyFromStreamAsync(imageStream)
-                            .ConfigureAwait(false);
-                    }
-                }
+                response.EnsureSuccessStatusCode();
+
+                using var imageStream = await response.Content.ReadAsStreamAsync()
+                    .ConfigureAwait(false);
+
+                return await MemoryImage.CopyFromStreamAsync(imageStream)
+                    .ConfigureAwait(false);
             }
         }
     }
index 28742a0..57b3f44 100644 (file)
@@ -97,15 +97,15 @@ namespace OpenTween.Thumbnail.Services
 
             var apiUrl = new Uri("http://api.tinami.com/content/info?" + MyCommon.BuildQueryString(query));
 
-            using (var response = await this.http.GetAsync(apiUrl, token).ConfigureAwait(false))
-            {
-                response.EnsureSuccessStatusCode();
+            using var response = await this.http.GetAsync(apiUrl, token)
+                .ConfigureAwait(false);
 
-                var xmlStr = await response.Content.ReadAsStringAsync()
-                    .ConfigureAwait(false);
+            response.EnsureSuccessStatusCode();
 
-                return XDocument.Parse(xmlStr);
-            }
+            var xmlStr = await response.Content.ReadAsStringAsync()
+                .ConfigureAwait(false);
+
+            return XDocument.Parse(xmlStr);
         }
     }
 }
index 58581ea..e9b1ef5 100644 (file)
@@ -68,14 +68,13 @@ namespace OpenTween.Thumbnail.Services
                 {
                     var apiConnection = TonTwitterCom.GetApiConnection();
 
-                    using (var imageStream = await apiConnection.GetStreamAsync(new Uri(this.ThumbnailImageUrl), null)
-                        .ConfigureAwait(false))
-                    {
-                        cancellationToken.ThrowIfCancellationRequested();
+                    using var imageStream = await apiConnection.GetStreamAsync(new Uri(this.ThumbnailImageUrl), null)
+                        .ConfigureAwait(false);
 
-                        return await MemoryImage.CopyFromStreamAsync(imageStream)
-                            .ConfigureAwait(false);
-                    }
+                    cancellationToken.ThrowIfCancellationRequested();
+
+                    return await MemoryImage.CopyFromStreamAsync(imageStream)
+                        .ConfigureAwait(false);
                 }, cancellationToken);
             }
         }
index 9e60fca..cee91f4 100644 (file)
@@ -74,15 +74,15 @@ namespace OpenTween.Thumbnail.Services
             try
             {
                 var apiUrl = string.Format("https://api.tumblr.com/v2/blog/{0}/posts?", host) + MyCommon.BuildQueryString(param);
-                using (var response = await this.http.GetAsync(apiUrl, token).ConfigureAwait(false))
-                {
-                    var jsonBytes = await response.Content.ReadAsByteArrayAsync()
-                        .ConfigureAwait(false);
+                using var response = await this.http.GetAsync(apiUrl, token)
+                    .ConfigureAwait(false);
+
+                var jsonBytes = await response.Content.ReadAsByteArrayAsync()
+                    .ConfigureAwait(false);
 
-                    var thumbs = ParsePhotoPostJson(jsonBytes);
+                var thumbs = ParsePhotoPostJson(jsonBytes);
 
-                    return thumbs.FirstOrDefault();
-                }
+                return thumbs.FirstOrDefault();
             }
             catch (XmlException) { }
             catch (HttpRequestException) { } // たまに api.tumblr.com が名前解決できない
@@ -92,27 +92,25 @@ namespace OpenTween.Thumbnail.Services
 
         internal static ThumbnailInfo[] ParsePhotoPostJson(byte[] jsonBytes)
         {
-            using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(jsonBytes, XmlDictionaryReaderQuotas.Max))
-            {
-                var xElm = XElement.Load(jsonReader);
+            using var jsonReader = JsonReaderWriterFactory.CreateJsonReader(jsonBytes, XmlDictionaryReaderQuotas.Max);
+            var xElm = XElement.Load(jsonReader);
 
-                var item = xElm.XPathSelectElement("/response/posts/item[1]");
-                if (item == null)
-                    return Array.Empty<ThumbnailInfo>();
+            var item = xElm.XPathSelectElement("/response/posts/item[1]");
+            if (item == null)
+                return Array.Empty<ThumbnailInfo>();
 
-                var postUrlElm = item.Element("post_url");
+            var postUrlElm = item.Element("post_url");
 
-                var thumbs =
-                    from photoElm in item.XPathSelectElements("photos/item/alt_sizes/item[1]/url")
-                    select new ThumbnailInfo
-                    {
-                        MediaPageUrl = postUrlElm.Value,
-                        ThumbnailImageUrl = photoElm.Value,
-                        TooltipText = null,
-                    };
+            var thumbs =
+                from photoElm in item.XPathSelectElements("photos/item/alt_sizes/item[1]/url")
+                select new ThumbnailInfo
+                {
+                    MediaPageUrl = postUrlElm.Value,
+                    ThumbnailImageUrl = photoElm.Value,
+                    TooltipText = null,
+                };
 
-                return thumbs.ToArray();
-            }
+            return thumbs.ToArray();
         }
     }
 }
index f15ef54..8ed7d56 100644 (file)
@@ -74,20 +74,20 @@ namespace OpenTween.Thumbnail
             MemoryImage image = null;
             try
             {
-                using (var response = await http.GetAsync(this.ThumbnailImageUrl, cancellationToken).ConfigureAwait(false))
-                {
-                    response.EnsureSuccessStatusCode();
+                using var response = await http.GetAsync(this.ThumbnailImageUrl, cancellationToken)
+                    .ConfigureAwait(false);
 
-                    using (var imageStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
-                    {
-                        image = await MemoryImage.CopyFromStreamAsync(imageStream)
-                            .ConfigureAwait(false);
+                response.EnsureSuccessStatusCode();
 
-                        cancellationToken.ThrowIfCancellationRequested();
+                using var imageStream = await response.Content.ReadAsStreamAsync()
+                    .ConfigureAwait(false);
 
-                        return image;
-                    }
-                }
+                image = await MemoryImage.CopyFromStreamAsync(imageStream)
+                    .ConfigureAwait(false);
+
+                cancellationToken.ThrowIfCancellationRequested();
+
+                return image;
             }
             catch (OperationCanceledException)
             {
index 4163fe2..7bd1bdb 100644 (file)
@@ -1950,10 +1950,8 @@ namespace OpenTween
                     {
                         dir = Path.Combine(dir, "Sounds");
                     }
-                    using (var player = new SoundPlayer(Path.Combine(dir, soundFile)))
-                    {
-                        player.Play();
-                    }
+                    using var player = new SoundPlayer(Path.Combine(dir, soundFile));
+                    player.Play();
                 }
                 catch (Exception)
                 {
@@ -3590,33 +3588,31 @@ namespace OpenTween
         {
             var result = DialogResult.Abort;
 
-            using (var settingDialog = new AppendSettingDialog())
-            {
-                settingDialog.Icon = this.MainIcon;
-                settingDialog.Owner = this;
-                settingDialog.ShowInTaskbar = showTaskbarIcon;
-                settingDialog.IntervalChanged += this.TimerInterval_Changed;
+            using var settingDialog = new AppendSettingDialog();
+            settingDialog.Icon = this.MainIcon;
+            settingDialog.Owner = this;
+            settingDialog.ShowInTaskbar = showTaskbarIcon;
+            settingDialog.IntervalChanged += this.TimerInterval_Changed;
 
-                settingDialog.tw = this.tw;
-                settingDialog.twitterApi = this.twitterApi;
+            settingDialog.tw = this.tw;
+            settingDialog.twitterApi = this.twitterApi;
 
-                settingDialog.LoadConfig(SettingManager.Common, SettingManager.Local);
+            settingDialog.LoadConfig(SettingManager.Common, SettingManager.Local);
 
-                try
-                {
-                    result = settingDialog.ShowDialog(this);
-                }
-                catch (Exception)
-                {
-                    return DialogResult.Abort;
-                }
+            try
+            {
+                result = settingDialog.ShowDialog(this);
+            }
+            catch (Exception)
+            {
+                return DialogResult.Abort;
+            }
 
-                if (result == DialogResult.OK)
+            if (result == DialogResult.OK)
+            {
+                lock (_syncObject)
                 {
-                    lock (_syncObject)
-                    {
-                        settingDialog.SaveConfig(SettingManager.Common, SettingManager.Local);
-                    }
+                    settingDialog.SaveConfig(SettingManager.Common, SettingManager.Local);
                 }
             }
 
@@ -4285,32 +4281,29 @@ namespace OpenTween
                 // 後付けのコントロールを破棄
                 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
                 {
-                    using (var label = _tabPage.Controls["labelUser"])
-                    {
-                        _tabPage.Controls.Remove(label);
-                    }
+                    using var label = _tabPage.Controls["labelUser"];
+                    _tabPage.Controls.Remove(label);
                 }
                 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
                 {
-                    using (var pnl = _tabPage.Controls["panelSearch"])
-                    {
-                        pnl.Enter -= SearchControls_Enter;
-                        pnl.Leave -= SearchControls_Leave;
-                        _tabPage.Controls.Remove(pnl);
+                    using var pnl = _tabPage.Controls["panelSearch"];
 
-                        foreach (Control ctrl in pnl.Controls)
+                    pnl.Enter -= SearchControls_Enter;
+                    pnl.Leave -= SearchControls_Leave;
+                    _tabPage.Controls.Remove(pnl);
+
+                    foreach (Control ctrl in pnl.Controls)
+                    {
+                        if (ctrl.Name == "buttonSearch")
                         {
-                            if (ctrl.Name == "buttonSearch")
-                            {
-                                ctrl.Click -= SearchButton_Click;
-                            }
-                            else if (ctrl.Name == "comboSearch")
-                            {
-                                ctrl.KeyDown -= SearchComboBox_KeyDown;
-                            }
-                            pnl.Controls.Remove(ctrl);
-                            ctrl.Dispose();
+                            ctrl.Click -= SearchButton_Click;
                         }
+                        else if (ctrl.Name == "comboSearch")
+                        {
+                            ctrl.KeyDown -= SearchComboBox_KeyDown;
+                        }
+                        pnl.Controls.Remove(ctrl);
+                        ctrl.Dispose();
                     }
                 }
 
@@ -5070,27 +5063,26 @@ namespace OpenTween
                         rctB.Width = e.Header.Width;
                         rctB.Height = fontHeight;
 
-                        using (var fnt = new Font(e.Item.Font, FontStyle.Bold))
-                        {
-                            TextRenderer.DrawText(e.Graphics,
-                                                    post.IsDeleted ? "(DELETED)" : post.TextSingleLine,
-                                                    e.Item.Font,
-                                                    Rectangle.Round(rct),
-                                                    color,
-                                                    TextFormatFlags.WordBreak |
-                                                    TextFormatFlags.EndEllipsis |
-                                                    TextFormatFlags.GlyphOverhangPadding |
-                                                    TextFormatFlags.NoPrefix);
-                            TextRenderer.DrawText(e.Graphics,
-                                                    e.Item.SubItems[4].Text + " / " + e.Item.SubItems[1].Text + " (" + e.Item.SubItems[3].Text + ") " + e.Item.SubItems[5].Text + e.Item.SubItems[6].Text + " [" + e.Item.SubItems[7].Text + "]",
-                                                    fnt,
-                                                    rctB,
-                                                    color,
-                                                    TextFormatFlags.SingleLine |
-                                                    TextFormatFlags.EndEllipsis |
-                                                    TextFormatFlags.GlyphOverhangPadding |
-                                                    TextFormatFlags.NoPrefix);
-                        }
+                        using var fnt = new Font(e.Item.Font, FontStyle.Bold);
+
+                        TextRenderer.DrawText(e.Graphics,
+                            post.IsDeleted ? "(DELETED)" : post.TextSingleLine,
+                            e.Item.Font,
+                            Rectangle.Round(rct),
+                            color,
+                            TextFormatFlags.WordBreak |
+                            TextFormatFlags.EndEllipsis |
+                            TextFormatFlags.GlyphOverhangPadding |
+                            TextFormatFlags.NoPrefix);
+                        TextRenderer.DrawText(e.Graphics,
+                            e.Item.SubItems[4].Text + " / " + e.Item.SubItems[1].Text + " (" + e.Item.SubItems[3].Text + ") " + e.Item.SubItems[5].Text + e.Item.SubItems[6].Text + " [" + e.Item.SubItems[7].Text + "]",
+                            fnt,
+                            rctB,
+                            color,
+                            TextFormatFlags.SingleLine |
+                            TextFormatFlags.EndEllipsis |
+                            TextFormatFlags.GlyphOverhangPadding |
+                            TextFormatFlags.NoPrefix);
                     }
                     else
                     {
@@ -5627,21 +5619,20 @@ namespace OpenTween
                 if (startup && versionInfo.Version <= SettingManager.Common.SkipUpdateVersion)
                     return;
 
-                using (var dialog = new UpdateDialog())
-                {
-                    dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
-                        MyCommon.GetReadableVersion(versionInfo.Version));
-                    dialog.DetailsText = versionInfo.ReleaseNote;
+                using var dialog = new UpdateDialog();
 
-                    if (dialog.ShowDialog(this) == DialogResult.Yes)
-                    {
-                        await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
-                    }
-                    else if (dialog.SkipButtonPressed)
-                    {
-                        SettingManager.Common.SkipUpdateVersion = versionInfo.Version;
-                        this.MarkSettingCommonModified();
-                    }
+                dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
+                    MyCommon.GetReadableVersion(versionInfo.Version));
+                dialog.DetailsText = versionInfo.ReleaseNote;
+
+                if (dialog.ShowDialog(this) == DialogResult.Yes)
+                {
+                    await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
+                }
+                else if (dialog.SkipButtonPressed)
+                {
+                    SettingManager.Common.SkipUpdateVersion = versionInfo.Version;
+                    this.MarkSettingCommonModified();
                 }
             }
             catch (Exception)
@@ -7347,41 +7338,41 @@ namespace OpenTween
             if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
             {
                 if (!SaveFileDialog1.ValidateNames) return;
-                using (var sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
+                using var sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8);
+                if (rslt == DialogResult.Yes)
+                {
+                    //All
+                    for (var idx = 0; idx < tab.AllCount; idx++)
+                    {
+                        var post = tab[idx];
+                        var protect = "";
+                        if (post.IsProtect)
+                            protect = "Protect";
+                        sw.WriteLine(post.Nickname + "\t" +
+                                 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
+                                 post.CreatedAt.ToLocalTimeString() + "\t" +
+                                 post.ScreenName + "\t" +
+                                 post.StatusId + "\t" +
+                                 post.ImageUrl + "\t" +
+                                 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
+                                 protect);
+                    }
+                }
+                else
                 {
-                    if (rslt == DialogResult.Yes)
+                    foreach (var post in this.CurrentTab.SelectedPosts)
                     {
-                        //All
-                        for (var idx = 0; idx < tab.AllCount; idx++)
-                        {
-                            var post = tab[idx];
-                            var protect = "";
-                            if (post.IsProtect) protect = "Protect";
-                            sw.WriteLine(post.Nickname + "\t" +
-                                     "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
-                                     post.CreatedAt.ToLocalTimeString() + "\t" +
-                                     post.ScreenName + "\t" +
-                                     post.StatusId + "\t" +
-                                     post.ImageUrl + "\t" +
-                                     "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
-                                     protect);
-                        }
-                    }
-                    else
-                    {
-                        foreach (var post in this.CurrentTab.SelectedPosts)
-                        {
-                            var protect = "";
-                            if (post.IsProtect) protect = "Protect";
-                            sw.WriteLine(post.Nickname + "\t" +
-                                     "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
-                                     post.CreatedAt.ToLocalTimeString() + "\t" +
-                                     post.ScreenName + "\t" +
-                                     post.StatusId + "\t" +
-                                     post.ImageUrl + "\t" +
-                                     "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
-                                     protect);
-                        }
+                        var protect = "";
+                        if (post.IsProtect)
+                            protect = "Protect";
+                        sw.WriteLine(post.Nickname + "\t" +
+                                 "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
+                                 post.CreatedAt.ToLocalTimeString() + "\t" +
+                                 post.ScreenName + "\t" +
+                                 post.StatusId + "\t" +
+                                 post.ImageUrl + "\t" +
+                                 "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
+                                 protect);
                     }
                 }
             }
@@ -8091,12 +8082,12 @@ namespace OpenTween
                 ListElement list = null;
                 if (tabUsage == MyCommon.TabUsageType.Lists)
                 {
-                    using (var listAvail = new ListAvailable())
-                    {
-                        if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
-                        if (listAvail.SelectedList == null) return;
-                        list = listAvail.SelectedList;
-                    }
+                    using var listAvail = new ListAvailable();
+                    if (listAvail.ShowDialog(this) == DialogResult.Cancel)
+                        return;
+                    if (listAvail.SelectedList == null)
+                        return;
+                    list = listAvail.SelectedList;
                 }
 
                 TabModel tab;
@@ -9562,38 +9553,32 @@ namespace OpenTween
                 // Firefox, Google Chrome で利用可能
                 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
 
-                using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
-                {
-                    var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
-                    if (lines.Length < 2)
-                        throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
+                using var stream = (MemoryStream)data.GetData("text/x-moz-url");
+                var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
+                if (lines.Length < 2)
+                    throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
 
-                    return (lines[0], lines[1]);
-                }
+                return (lines[0], lines[1]);
             }
             else if (data.GetDataPresent("IESiteModeToUrl"))
             {
                 // Internet Exproler 用
                 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
 
-                using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
-                {
-                    var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
-                    if (lines.Length < 2)
-                        throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
+                using var stream = (MemoryStream)data.GetData("IESiteModeToUrl");
+                var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
+                if (lines.Length < 2)
+                    throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
 
-                    return (lines[0], lines[1]);
-                }
+                return (lines[0], lines[1]);
             }
             else if (data.GetDataPresent("UniformResourceLocatorW"))
             {
                 // それ以外のブラウザ向け
 
-                using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
-                {
-                    var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
-                    return (url, null);
-                }
+                using var stream = (MemoryStream)data.GetData("UniformResourceLocatorW");
+                var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
+                return (url, null);
             }
 
             throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
@@ -10177,10 +10162,8 @@ namespace OpenTween
                 }
             }
 
-            using (var apiDlg = new ApiInfoDialog())
-            {
-                apiDlg.ShowDialog(this);
-            }
+            using var apiDlg = new ApiInfoDialog();
+            apiDlg.ShowDialog(this);
         }
 
         private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
@@ -10234,19 +10217,17 @@ namespace OpenTween
         {
             if (!skipInput)
             {
-                using (var inputName = new InputTabName())
-                {
-                    inputName.FormTitle = "Unfollow";
-                    inputName.FormDescription = Properties.Resources.FRMessage1;
-                    inputName.TabName = id;
+                using var inputName = new InputTabName();
+                inputName.FormTitle = "Unfollow";
+                inputName.FormDescription = Properties.Resources.FRMessage1;
+                inputName.TabName = id;
 
-                    if (inputName.ShowDialog(this) != DialogResult.OK)
-                        return;
-                    if (string.IsNullOrWhiteSpace(inputName.TabName))
-                        return;
+                if (inputName.ShowDialog(this) != DialogResult.OK)
+                    return;
+                if (string.IsNullOrWhiteSpace(inputName.TabName))
+                    return;
 
-                    id = inputName.TabName.Trim();
-                }
+                id = inputName.TabName.Trim();
             }
 
             using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
@@ -10657,10 +10638,8 @@ namespace OpenTween
 
         public void ListManageUserContext(string screenName)
         {
-            using (var listSelectForm = new MyLists(screenName, this.twitterApi))
-            {
-                listSelectForm.ShowDialog(this);
-            }
+            using var listSelectForm = new MyLists(screenName, this.twitterApi);
+            listSelectForm.ShowDialog(this);
         }
 
         private void SearchControls_Enter(object sender, EventArgs e)
@@ -10946,19 +10925,17 @@ namespace OpenTween
 
             if (ShowInputDialog)
             {
-                using (var inputName = new InputTabName())
-                {
-                    inputName.FormTitle = "Show UserStatus";
-                    inputName.FormDescription = Properties.Resources.FRMessage1;
-                    inputName.TabName = id;
+                using var inputName = new InputTabName();
+                inputName.FormTitle = "Show UserStatus";
+                inputName.FormDescription = Properties.Resources.FRMessage1;
+                inputName.TabName = id;
 
-                    if (inputName.ShowDialog(this) != DialogResult.OK)
-                        return;
-                    if (string.IsNullOrWhiteSpace(inputName.TabName))
-                        return;
+                if (inputName.ShowDialog(this) != DialogResult.OK)
+                    return;
+                if (string.IsNullOrWhiteSpace(inputName.TabName))
+                    return;
 
-                    id = inputName.TabName.Trim();
-                }
+                id = inputName.TabName.Trim();
             }
 
             using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
@@ -10986,17 +10963,15 @@ namespace OpenTween
 
         private async Task doShowUserStatus(TwitterUser user)
         {
-            using (var userDialog = new UserInfoDialog(this, this.twitterApi))
-            {
-                var showUserTask = userDialog.ShowUserAsync(user);
-                userDialog.ShowDialog(this);
+            using var userDialog = new UserInfoDialog(this, this.twitterApi);
+            var showUserTask = userDialog.ShowUserAsync(user);
+            userDialog.ShowDialog(this);
 
-                this.Activate();
-                this.BringToFront();
+            this.Activate();
+            this.BringToFront();
 
-                // ユーザー情報の表示が完了するまで userDialog を破棄しない
-                await showUserTask;
-            }
+            // ユーザー情報の表示が完了するまで userDialog を破棄しない
+            await showUserTask;
         }
 
         internal Task ShowUserStatus(string id, bool ShowInputDialog)
@@ -11181,10 +11156,8 @@ namespace OpenTween
                                    == DialogResult.OK)
                     {
                         // clipboardから画像を取得
-                        using (var image = Clipboard.GetImage())
-                        {
-                            this.ImageSelector.BeginSelection(image);
-                        }
+                        using var image = Clipboard.GetImage();
+                        this.ImageSelector.BeginSelection(image);
                     }
                 }
             }
@@ -11197,10 +11170,8 @@ namespace OpenTween
 
         private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
         {
-            using (var form = new ListManage(tw))
-            {
-                form.ShowDialog(this);
-            }
+            using var form = new ListManage(tw);
+            form.ShowDialog(this);
         }
 
         private bool ModifySettingCommon { get; set; }
@@ -11553,10 +11524,8 @@ namespace OpenTween
                         {
                             dir = Path.Combine(dir, "Sounds");
                         }
-                        using (var player = new SoundPlayer(Path.Combine(dir, snd)))
-                        {
-                            player.Play();
-                        }
+                        using var player = new SoundPlayer(Path.Combine(dir, snd));
+                        player.Play();
                     }
                     catch (Exception)
                     {
@@ -11686,20 +11655,19 @@ namespace OpenTween
         {
             var id = this.CurrentPost?.ScreenName ?? "";
 
-            using (var inputName = new InputTabName())
+            using var inputName = new InputTabName();
+            inputName.FormTitle = caption;
+            inputName.FormDescription = Properties.Resources.FRMessage1;
+            inputName.TabName = id;
+
+            if (inputName.ShowDialog() == DialogResult.OK &&
+                !string.IsNullOrEmpty(inputName.TabName.Trim()))
             {
-                inputName.FormTitle = caption;
-                inputName.FormDescription = Properties.Resources.FRMessage1;
-                inputName.TabName = id;
-                if (inputName.ShowDialog() == DialogResult.OK &&
-                    !string.IsNullOrEmpty(inputName.TabName.Trim()))
-                {
-                    id = inputName.TabName.Trim();
-                }
-                else
-                {
-                    id = "";
-                }
+                id = inputName.TabName.Trim();
+            }
+            else
+            {
+                id = "";
             }
             return id;
         }
index 8d50b7b..7e2c241 100644 (file)
@@ -718,18 +718,15 @@ namespace OpenTween
             {
                 try
                 {
-                    using (Image orgBmp = new Bitmap(IconCache.TryGetFromCache(imageUrl).Image))
+                    using var orgBmp = new Bitmap(IconCache.TryGetFromCache(imageUrl).Image);
+                    using var bmp2 = new Bitmap(orgBmp.Size.Width, orgBmp.Size.Height);
+
+                    using (var g = Graphics.FromImage(bmp2))
                     {
-                        using (var bmp2 = new Bitmap(orgBmp.Size.Width, orgBmp.Size.Height))
-                        {
-                            using (var g = Graphics.FromImage(bmp2))
-                            {
-                                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
-                                g.DrawImage(orgBmp, 0, 0, orgBmp.Size.Width, orgBmp.Size.Height);
-                            }
-                            bmp2.Save(this.Owner.SaveFileDialog1.FileName);
-                        }
+                        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
+                        g.DrawImage(orgBmp, 0, 0, orgBmp.Size.Width, orgBmp.Size.Height);
                     }
+                    bmp2.Save(this.Owner.SaveFileDialog1.FileName);
                 }
                 catch (Exception)
                 {
index b266814..47c4da7 100644 (file)
@@ -202,19 +202,19 @@ namespace OpenTween
             {
                 var uri = imageUri.Replace("_normal", "_bigger");
 
-                using (var imageStream = await Networking.Http.GetStreamAsync(uri).ConfigureAwait(false))
-                {
-                    var image = await MemoryImage.CopyFromStreamAsync(imageStream)
-                        .ConfigureAwait(false);
+                using var imageStream = await Networking.Http.GetStreamAsync(uri)
+                    .ConfigureAwait(false);
 
-                    if (cancellationToken.IsCancellationRequested)
-                    {
-                        image.Dispose();
-                        throw new OperationCanceledException(cancellationToken);
-                    }
+                var image = await MemoryImage.CopyFromStreamAsync(imageStream)
+                    .ConfigureAwait(false);
 
-                    return image;
+                if (cancellationToken.IsCancellationRequested)
+                {
+                    image.Dispose();
+                    throw new OperationCanceledException(cancellationToken);
                 }
+
+                return image;
             });
         }