Ejemplo n.º 1
0
        /// <summary>Snippet for CreateApiConfig</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void CreateApiConfigRequestObject()
        {
            // Create client
            ApiGatewayServiceClient apiGatewayServiceClient = ApiGatewayServiceClient.Create();
            // Initialize request argument(s)
            CreateApiConfigRequest request = new CreateApiConfigRequest
            {
                ParentAsApiName = ApiName.FromProjectApi("[PROJECT]", "[API]"),
                ApiConfigId     = "",
                ApiConfig       = new ApiConfig(),
            };
            // Make the request
            Operation <ApiConfig, OperationMetadata> response = apiGatewayServiceClient.CreateApiConfig(request);

            // Poll until the returned long-running operation is complete
            Operation <ApiConfig, OperationMetadata> completedResponse = response.PollUntilCompleted();
            // Retrieve the operation result
            ApiConfig result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            Operation <ApiConfig, OperationMetadata> retrievedResponse = apiGatewayServiceClient.PollOnceCreateApiConfig(operationName);

            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                ApiConfig retrievedResult = retrievedResponse.Result;
            }
        }
        public void GetApiResourceNames()
        {
            moq::Mock <ApiGatewayService.ApiGatewayServiceClient> mockGrpcClient = new moq::Mock <ApiGatewayService.ApiGatewayServiceClient>(moq::MockBehavior.Strict);

            mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock <lro::Operations.OperationsClient>().Object);
            GetApiRequest request = new GetApiRequest
            {
                ApiName = ApiName.FromProjectApi("[PROJECT]", "[API]"),
            };
            Api expectedResponse = new Api
            {
                ApiName    = ApiName.FromProjectApi("[PROJECT]", "[API]"),
                CreateTime = new wkt::Timestamp(),
                UpdateTime = new wkt::Timestamp(),
                Labels     =
                {
                    {
                        "key8a0b6e3c",
                        "value60c16320"
                    },
                },
                DisplayName = "display_name137f65c2",
                ManagedServiceAsManagedServiceName = ManagedServiceName.FromService("[SERVICE]"),
                State = Api.Types.State.Unspecified,
            };

            mockGrpcClient.Setup(x => x.GetApi(request, moq::It.IsAny <grpccore::CallOptions>())).Returns(expectedResponse);
            ApiGatewayServiceClient client = new ApiGatewayServiceClientImpl(mockGrpcClient.Object, null);
            Api response = client.GetApi(request.ApiName);

            xunit::Assert.Same(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }
        /// <summary>Snippet for DeleteApiAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task DeleteApiResourceNamesAsync()
        {
            // Create client
            ApiGatewayServiceClient apiGatewayServiceClient = await ApiGatewayServiceClient.CreateAsync();

            // Initialize request argument(s)
            ApiName name = ApiName.FromProjectApi("[PROJECT]", "[API]");
            // Make the request
            Operation <Empty, OperationMetadata> response = await apiGatewayServiceClient.DeleteApiAsync(name);

            // Poll until the returned long-running operation is complete
            Operation <Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();

            // Retrieve the operation result
            Empty result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            Operation <Empty, OperationMetadata> retrievedResponse = await apiGatewayServiceClient.PollOnceDeleteApiAsync(operationName);

            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Empty retrievedResult = retrievedResponse.Result;
            }
        }
Ejemplo n.º 4
0
        public static void Log(ApiName apiName, String data, String logType)
        {
            String logPath  = StairSupplies.Library.LOG_PATH;
            String filePath = "";


            if (logPath == "")
            {
                return;
            }
            if (data == "")
            {
                return;
            }
            if (logType == "")
            {
                return;
            }
            filePath = logPath + apiName + "/" + logType.ToLower() + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";


            if (Directory.Exists(logPath))
            {
                if (!Directory.Exists(logPath + apiName))
                {
                    Directory.CreateDirectory(logPath + apiName);
                }
                if (!Directory.Exists(logPath + apiName + "/" + logType.ToLower()))
                {
                    Directory.CreateDirectory(logPath + apiName + "/" + logType.ToLower());
                }

                File.AppendAllText(filePath, DateTime.UtcNow.ToString("MM-dd-yyyy hh:mm:sstt") + "\t" + data + "\r\n");
            }
        }
Ejemplo n.º 5
0
 /// <summary>Snippet for GetApi</summary>
 /// <remarks>
 /// This snippet has been automatically generated for illustrative purposes only.
 /// It may require modifications to work in your environment.
 /// </remarks>
 public void GetApiResourceNames()
 {
     // Create client
     ApiGatewayServiceClient apiGatewayServiceClient = ApiGatewayServiceClient.Create();
     // Initialize request argument(s)
     ApiName name = ApiName.FromProjectApi("[PROJECT]", "[API]");
     // Make the request
     Api response = apiGatewayServiceClient.GetApi(name);
 }
Ejemplo n.º 6
0
        /// <summary>Snippet for GetApiAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task GetApiResourceNamesAsync()
        {
            // Create client
            ApiGatewayServiceClient apiGatewayServiceClient = await ApiGatewayServiceClient.CreateAsync();

            // Initialize request argument(s)
            ApiName name = ApiName.FromProjectApi("[PROJECT]", "[API]");
            // Make the request
            Api response = await apiGatewayServiceClient.GetApiAsync(name);
        }
 /// <summary>
 /// Returns a hash code for this instance.
 /// </summary>
 /// <returns>
 /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
 /// </returns>
 public override int GetHashCode()
 {
     unchecked
     {
         int result = 0;
         result = (result * 397) ^ (ApiName != null ? ApiName.GetHashCode() : 0);
         result = (result * 397) ^ (Game != null ? Game.GetHashCode() : 0);
         result = (result * 397) ^ (Language != null ? Language.GetHashCode() : 0);
         return(result);
     }
 }
Ejemplo n.º 8
0
 /// <summary>Snippet for GetApi</summary>
 /// <remarks>
 /// This snippet has been automatically generated for illustrative purposes only.
 /// It may require modifications to work in your environment.
 /// </remarks>
 public void GetApiRequestObject()
 {
     // Create client
     ApiGatewayServiceClient apiGatewayServiceClient = ApiGatewayServiceClient.Create();
     // Initialize request argument(s)
     GetApiRequest request = new GetApiRequest
     {
         ApiName = ApiName.FromProjectApi("[PROJECT]", "[API]"),
     };
     // Make the request
     Api response = apiGatewayServiceClient.GetApi(request);
 }
 /// <summary>
 /// Returns a hash code for this instance.
 /// </summary>
 /// <returns>
 /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
 /// </returns>
 public override int GetHashCode()
 {
     unchecked
     {
         int result = Id;
         result = (result * 397) ^ (ApiName != null ? ApiName.GetHashCode() : 0);
         result = (result * 397) ^ (ImageUrl != null ? ImageUrl.GetHashCode() : 0);
         result = (result * 397) ^ (Name != null ? Name.GetHashCode() : 0);
         result = (result * 397) ^ (Description != null ? Description.GetHashCode() : 0);
         return(result);
     }
 }
        /// <summary>Snippet for ListApiConfigsAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task ListApiConfigsRequestObjectAsync()
        {
            // Create client
            ApiGatewayServiceClient apiGatewayServiceClient = await ApiGatewayServiceClient.CreateAsync();

            // Initialize request argument(s)
            ListApiConfigsRequest request = new ListApiConfigsRequest
            {
                ParentAsApiName = ApiName.FromProjectApi("[PROJECT]", "[API]"),
                Filter          = "",
                OrderBy         = "",
            };
            // Make the request
            PagedAsyncEnumerable <ListApiConfigsResponse, ApiConfig> response = apiGatewayServiceClient.ListApiConfigsAsync(request);

            // Iterate over all response items, lazily performing RPCs as required
            await response.ForEachAsync((ApiConfig item) =>
            {
                // Do something with each item
                Console.WriteLine(item);
            });

            // Or iterate over pages (of server-defined size), performing one RPC per page
            await response.AsRawResponses().ForEachAsync((ListApiConfigsResponse page) =>
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (ApiConfig item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            });

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page <ApiConfig> singlePage = await response.ReadPageAsync(pageSize);

            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (ApiConfig item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
        }
Ejemplo n.º 11
0
        async Task SaveSettingsInApp()
        {
            string newServerApi = ServerApi.Trim();
            string newapiName   = ApiName.Trim();

            if (!string.IsNullOrEmpty(newServerApi))
            {
                _SettingsApp.SetUrlApi = newServerApi;
            }
            if (!string.IsNullOrEmpty(newapiName))
            {
                _SettingsApp.SetApiName = newapiName;
            }
            await apiServices.LogoutUser();

            App.Current.MainPage = new NavigationPage(new MainPage());
        }
        /// <summary>Snippet for ListApiConfigs</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void ListApiConfigsResourceNames()
        {
            // Create client
            ApiGatewayServiceClient apiGatewayServiceClient = ApiGatewayServiceClient.Create();
            // Initialize request argument(s)
            ApiName parent = ApiName.FromProjectApi("[PROJECT]", "[API]");
            // Make the request
            PagedEnumerable <ListApiConfigsResponse, ApiConfig> response = apiGatewayServiceClient.ListApiConfigs(parent);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (ApiConfig item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (ListApiConfigsResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (ApiConfig item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page <ApiConfig> singlePage = response.ReadPage(pageSize);

            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (ApiConfig item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
        }
        public async stt::Task GetApiResourceNamesAsync()
        {
            moq::Mock <ApiGatewayService.ApiGatewayServiceClient> mockGrpcClient = new moq::Mock <ApiGatewayService.ApiGatewayServiceClient>(moq::MockBehavior.Strict);

            mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock <lro::Operations.OperationsClient>().Object);
            GetApiRequest request = new GetApiRequest
            {
                ApiName = ApiName.FromProjectApi("[PROJECT]", "[API]"),
            };
            Api expectedResponse = new Api
            {
                ApiName    = ApiName.FromProjectApi("[PROJECT]", "[API]"),
                CreateTime = new wkt::Timestamp(),
                UpdateTime = new wkt::Timestamp(),
                Labels     =
                {
                    {
                        "key8a0b6e3c",
                        "value60c16320"
                    },
                },
                DisplayName = "display_name137f65c2",
                ManagedServiceAsManagedServiceName = ManagedServiceName.FromService("[SERVICE]"),
                State = Api.Types.State.Unspecified,
            };

            mockGrpcClient.Setup(x => x.GetApiAsync(request, moq::It.IsAny <grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall <Api>(stt::Task.FromResult(expectedResponse), null, null, null, null));
            ApiGatewayServiceClient client = new ApiGatewayServiceClientImpl(mockGrpcClient.Object, null);
            Api responseCallSettings       = await client.GetApiAsync(request.ApiName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));

            xunit::Assert.Same(expectedResponse, responseCallSettings);
            Api responseCancellationToken = await client.GetApiAsync(request.ApiName, st::CancellationToken.None);

            xunit::Assert.Same(expectedResponse, responseCancellationToken);
            mockGrpcClient.VerifyAll();
        }
Ejemplo n.º 14
0
        /// <summary>
        /// 生成请求对象
        /// </summary>
        public void CreateRequest()
        {
            var url = new StringBuilder();

            url.Append($"{Host?.TrimEnd('/') + "/"}{ApiName?.TrimStart('/')}");

            if (Query != null && Query.Count > 0)
            {
                bool first = true;
                foreach (var kvp in Query)
                {
                    if (string.IsNullOrEmpty(kvp.Key) || kvp.Value == null)
                    {
                        continue;
                    }
                    if (first)
                    {
                        first = false;
                        url.Append('?');
                    }
                    else
                    {
                        url.Append('&');
                    }
                    url.Append($"{kvp.Key}={HttpUtility.UrlEncode(kvp.Value, Encoding.UTF8)}");
                }
            }
            RemoteUrl     = url.ToString();
            RemoteRequest = (HttpWebRequest)WebRequest.Create(RemoteUrl);
            RemoteRequest.Headers.Add(HttpRequestHeader.Authorization, Authorization);
            RemoteRequest.Timeout   = ConfigurationManager.AppSettings.GetInt("httpTimeout", 30);
            RemoteRequest.Method    = Method;
            RemoteRequest.KeepAlive = true;

            if (Form != null && Form.Count > 0)
            {
                RemoteRequest.ContentType = "application/x-www-form-urlencoded";
                var  builder = new StringBuilder();
                bool first   = true;
                foreach (var kvp in Form)
                {
                    if (string.IsNullOrEmpty(kvp.Key) || kvp.Value == null)
                    {
                        continue;
                    }
                    if (first)
                    {
                        first = false;
                    }
                    else
                    {
                        url.Append('&');
                    }
                    builder.Append($"{kvp.Key}={HttpUtility.UrlEncode(kvp.Value, Encoding.UTF8)}");
                }

                using (var rs = RemoteRequest.GetRequestStream())
                {
                    var formData = Encoding.UTF8.GetBytes(builder.ToString());
                    rs.Write(formData, 0, formData.Length);
                }
            }
            else if (!string.IsNullOrWhiteSpace(Json))
            {
                RemoteRequest.ContentType = "application/json;charset=utf-8";
                var buffer = Json.ToUtf8Bytes();
                using (var rs = RemoteRequest.GetRequestStream())
                {
                    rs.Write(buffer, 0, buffer.Length);
                }
            }
            else
            {
                RemoteRequest.ContentType = "application/x-www-form-urlencoded";
            }
        }
Ejemplo n.º 15
0
        public XDocument GenerateProjectFile()
        {
            // This comment is turned into a line break later (in CodeGenerator).
            // While this is ugly, it's the simplest way of getting line breaks exactly where we want them.
            var lineBreak         = new XComment("linebreak");
            var packageProperties = new XElement("PropertyGroup",
                                                 new XElement("Title", $"{PackageName} Client Library"),
                                                 new XElement("Version", $"{Features.ReleaseVersion}.{GetRevision()}"),
                                                 new XElement("Authors", "Google Inc."),
                                                 // TODO: Update this to the current year, both here and in Python?
                                                 new XElement("Copyright", $"Copyright 2017 {(_discoveryDoc.OwnerName == "Google" ? "Google Inc." : _discoveryDoc.OwnerName)}"),
                                                 new XElement("PackageTags", "Google"),
                                                 new XElement("PackageProjectUrl", "https://github.com/google/google-api-dotnet-client"),
                                                 new XElement("PackageLicenseFile", "LICENSE"),
                                                 new XElement("RepositoryType", "git"),
                                                 new XElement("RepositoryUrl", "https://github.com/google/google-api-dotnet-client"),
                                                 new XElement("PackageIconUrl", "https://www.gstatic.com/images/branding/product/1x/google_developers_64dp.png"),
                                                 new XElement("Description", GetApiDescription())
                                                 );

            var licenseItemGroup = new XElement("ItemGroup",
                                                new XElement("None", new XAttribute("Include", "../../../LICENSE"), new XAttribute("Pack", "true"), new XAttribute("PackagePath", ""))
                                                );

            var buildProperties = new XElement("PropertyGroup",
                                               new XElement("TargetFrameworks", "netstandard2.0;netstandard1.3;netstandard1.0;net45;net40"),
                                               new XElement("SignAssembly", "true"),
                                               new XElement("AssemblyOriginatorKeyFile", @"..\..\..\google.apis.snk"),
                                               new XElement("DebugType", "portable"),
                                               new XElement("GenerateDocumentationFile", "true"),
                                               new XElement("NoWarn", "1570,1587,1591")
                                               );

            var commonDependencies = new XElement("ItemGroup",
                                                  PackageReference("ConfigureAwaitChecker.Analyzer", "1.0.1", new XAttribute("PrivateAssets", "All")),
                                                  PackageReference("SourceLink.Create.CommandLine", "2.8.0", new XAttribute("PrivateAssets", "All"))
                                                  );

            var netstandard20 = new XElement("ItemGroup", FrameworkCondition("netstandard2.0"),
                                             PackageReference("Google.Apis", Features.CurrentSupportVersion),
                                             AuthScopes.Any() ? PackageReference("Google.Apis.Auth", Features.CurrentSupportVersion) : null
                                             );

            var netstandard13 = new XElement("ItemGroup", FrameworkCondition("netstandard1.3"),
                                             PackageReference("Google.Apis", Features.CurrentSupportVersion),
                                             AuthScopes.Any() ? PackageReference("Google.Apis.Auth", Features.CurrentSupportVersion) : null
                                             );

            var netstandard10Properties = new XElement("PropertyGroup", FrameworkCondition("netstandard1.0"),
                                                       new XElement("PackageTargetFallback", "portable-net45+win8+wpa81+wp8"),
                                                       new XElement("AppConfig", "app.netstandard10.config")
                                                       );
            var netstandard10Items = new XElement("ItemGroup", FrameworkCondition("netstandard1.0"),
                                                  PackageReference("Google.Apis", $"[{Features.PclSupportVersion}]", new XAttribute("ExcludeAssets", "build")),
                                                  AuthScopes.Any() ? PackageReference("Google.Apis.Auth", $"[{Features.PclSupportVersion}]", new XAttribute("ExcludeAssets", "build")) : null,
                                                  PackageReference("Microsoft.NETCore.Portable.Compatibility", "1.0.1")
                                                  );

            var net45 = new XElement("ItemGroup", FrameworkCondition("net45"),
                                     PackageReference("Google.Apis", Features.CurrentSupportVersion),
                                     AuthScopes.Any() ? PackageReference("Google.Apis.Auth", Features.CurrentSupportVersion) : null
                                     );

            var net40Properties = new XElement("PropertyGroup", FrameworkCondition("net40"),
                                               new XElement("AutoUnifyAssemblyReferences", "false"),
                                               new XElement("AppConfig", "app.net40.config")
                                               );
            var net40Items = new XElement("ItemGroup", FrameworkCondition("net40"),
                                          PackageReference("Google.Apis", $"[{Features.Net40SupportVersion}]", new XAttribute("ExcludeAssets", "build")),
                                          AuthScopes.Any() ? PackageReference("Google.Apis.Auth", $"[{Features.Net40SupportVersion}]", new XAttribute("ExcludeAssets", "build")) : null
                                          );

            var project = new XElement("Project", new XAttribute("Sdk", "Microsoft.NET.Sdk"), new XAttribute("ToolsVersion", "15.0"),
                                       lineBreak, new XComment(" nupkg information "), packageProperties,
                                       lineBreak, licenseItemGroup,
                                       lineBreak, new XComment(" build properties "), buildProperties,
                                       lineBreak, new XComment(" common dependencies "), commonDependencies,
                                       lineBreak, new XComment(" per-target dependencies "),
                                       netstandard20,
                                       lineBreak, netstandard13,
                                       lineBreak, netstandard10Properties, netstandard10Items,
                                       lineBreak, net45,
                                       lineBreak, net40Properties, net40Items,
                                       lineBreak
                                       );

            return(new XDocument(project));

            int GetRevision()
            {
                // For some reason we don't rev the Discovery API...
                if (ApiName == "discovery")
                {
                    return(0);
                }
                string discoveryRevision = _discoveryDoc.Revision;

                // If the revision is a date string, the revision is the number of days since 2015-01-01,
                // unless the revision is before 2015, in which case it's 0.
                if (DateTime.TryParseExact(discoveryRevision, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out var date))
                {
                    return(date.Year < 2015 ? 0 : (int)(date - new DateTime(2015, 1, 1)).TotalDays);
                }
                return(int.Parse(discoveryRevision));
            }

            string GetApiDescription()
            {
                var prefix = Features.CloudPackageMap.TryGetValue(PackageName, out var cloudPackage)
                    ? $@"
      This is not the recommended package for working with {ApiName.ToUpperCamelCase()}, please use the {cloudPackage} package.
      This Google APIs Client Library for working with {ApiName.ToUpperCamelCase()} {ApiVersion} uses older code generation, and is harder to use."
                    : $"\n      Google APIs Client Library for working with {ApiName.ToUpperCamelCase()} {ApiVersion}.";
                // The part of the package description that's the same for all packages - but can't be a constant due to the ApiName/ApiVersion part of the link.
                string suffix = @$ "

      Supported Platforms:
      - .NET Framework 4.5+
      - .NET Standard 1.3 and .NET Standard 2.0; providing .NET Core support.

      Legacy platforms:
      - .NET Framework 4.0
      - Windows 8 Apps
      - Windows Phone 8.1
      - Windows Phone Silverlight 8.0

      Incompatible platforms:
      - .NET Framework < 4.0
      - Silverlight
      - UWP (will build, but is known not to work at runtime)
      - Xamarin

      More documentation on the API is available at:
      https://developers.google.com/api-client-library/dotnet/apis/{ApiName}/{ApiVersion}

      The package source code is available at:
      https://github.com/google/google-api-dotnet-client/tree/master/Src/Generated
    ";

                return(prefix + suffix);
            }

            XElement PackageReference(string name, string version, params XAttribute[] extraAttributes) =>
Ejemplo n.º 16
0
 public override int GetHashCode()
 {
     return(ApiName.GetHashCode());
 }
            /// <param name="symbol">The symbol to analyze.</param>
            /// <param name="reportDiagnostic">Action called to actually report a diagnostic.</param>
            /// <param name="isImplicitlyDeclaredConstructor">If the symbol is an implicitly declared constructor.</param>
            /// <param name="explicitLocation">A location to report the diagnostics for a symbol at. If null, then
            /// the location of the symbol will be used.</param>
            private void OnSymbolActionCore(ISymbol symbol, Action <Diagnostic> reportDiagnostic, bool isImplicitlyDeclaredConstructor, Location?explicitLocation = null)
            {
                Debug.Assert(IsPublicAPI(symbol));

                ApiName publicApiName = GetPublicApiName(symbol);

                _visitedApiList.TryAdd(publicApiName.Name, default);
                _visitedApiList.TryAdd(WithObliviousMarker(publicApiName.Name), default);
                _visitedApiList.TryAdd(publicApiName.NameWithNullability, default);
                _visitedApiList.TryAdd(WithObliviousMarker(publicApiName.NameWithNullability), default);

                List <Location> locationsToReport = new List <Location>();

                if (explicitLocation != null)
                {
                    locationsToReport.Add(explicitLocation);
                }
                else
                {
                    var locations = isImplicitlyDeclaredConstructor ? symbol.ContainingType.Locations : symbol.Locations;
                    locationsToReport.AddRange(locations.Where(l => l.IsInSource));
                }

                ApiLine foundApiLine;
                bool    symbolUsesOblivious = false;

                if (_useNullability)
                {
                    symbolUsesOblivious = UsesOblivious(symbol);
                    if (symbolUsesOblivious)
                    {
                        reportObliviousApi(symbol);
                    }

                    var hasPublicApiEntryWithNullability = _publicApiMap.TryGetValue(publicApiName.NameWithNullability, out foundApiLine);

                    var hasPublicApiEntryWithNullabilityAndOblivious =
                        !hasPublicApiEntryWithNullability &&
                        symbolUsesOblivious &&
                        _publicApiMap.TryGetValue(WithObliviousMarker(publicApiName.NameWithNullability), out foundApiLine);

                    if (!hasPublicApiEntryWithNullability && !hasPublicApiEntryWithNullabilityAndOblivious)
                    {
                        var hasPublicApiEntryWithoutNullability = _publicApiMap.TryGetValue(publicApiName.Name, out foundApiLine);

                        var hasPublicApiEntryWithoutNullabilityButOblivious =
                            !hasPublicApiEntryWithoutNullability &&
                            _publicApiMap.TryGetValue(WithObliviousMarker(publicApiName.Name), out foundApiLine);

                        if (!hasPublicApiEntryWithoutNullability && !hasPublicApiEntryWithoutNullabilityButOblivious)
                        {
                            reportDeclareNewApi(symbol, isImplicitlyDeclaredConstructor, withObliviousIfNeeded(publicApiName.NameWithNullability));
                        }
                        else
                        {
                            reportAnnotateApi(symbol, isImplicitlyDeclaredConstructor, publicApiName, foundApiLine.IsShippedApi);
                        }
                    }
                    else if (hasPublicApiEntryWithNullability && symbolUsesOblivious)
                    {
                        reportAnnotateApi(symbol, isImplicitlyDeclaredConstructor, publicApiName, foundApiLine.IsShippedApi);
                    }
                }
                else
                {
                    var hasPublicApiEntryWithoutNullability = _publicApiMap.TryGetValue(publicApiName.Name, out foundApiLine);
                    if (!hasPublicApiEntryWithoutNullability)
                    {
                        reportDeclareNewApi(symbol, isImplicitlyDeclaredConstructor, publicApiName.Name);
                    }

                    if (publicApiName.Name != publicApiName.NameWithNullability)
                    {
                        // '#nullable enable' would be useful and should be set
                        reportDiagnosticAtLocations(ShouldAnnotateApiFilesRule, ImmutableDictionary <string, string> .Empty);
                    }
                }

                if (symbol.Kind == SymbolKind.Method)
                {
                    var method             = (IMethodSymbol)symbol;
                    var isMethodShippedApi = foundApiLine?.IsShippedApi == true;

                    // Check if a public API is a constructor that makes this class instantiable, even though the base class
                    // is not instantiable. That API pattern is not allowed, because it causes protected members of
                    // the base class, which are not considered public APIs, to be exposed to subclasses of this class.
                    if (!isMethodShippedApi &&
                        method.MethodKind == MethodKind.Constructor &&
                        method.ContainingType.TypeKind == TypeKind.Class &&
                        !method.ContainingType.IsSealed &&
                        method.ContainingType.BaseType != null &&
                        IsPublicApiCore(method.ContainingType.BaseType) &&
                        !CanTypeBeExtendedPublicly(method.ContainingType.BaseType))
                    {
                        string errorMessageName = GetErrorMessageName(method, isImplicitlyDeclaredConstructor);
                        ImmutableDictionary <string, string> propertyBag = ImmutableDictionary <string, string> .Empty;
                        var locations = isImplicitlyDeclaredConstructor ? method.ContainingType.Locations : method.Locations;
                        reportDiagnostic(Diagnostic.Create(ExposedNoninstantiableType, locations[0], propertyBag, errorMessageName));
                    }

                    // Flag public API with optional parameters that violate backcompat requirements: https://github.com/dotnet/roslyn/blob/master/docs/Adding%20Optional%20Parameters%20in%20Public%20API.md.
                    if (method.HasOptionalParameters())
                    {
                        foreach (var overload in method.GetOverloads())
                        {
                            if (!IsPublicAPI(overload))
                            {
                                continue;
                            }

                            // Don't flag overloads which have identical params (e.g. overloading a generic and non-generic method with same parameter types).
                            if (overload.Parameters.Length == method.Parameters.Length &&
                                overload.Parameters.Select(p => p.Type).SequenceEqual(method.Parameters.Select(p => p.Type)))
                            {
                                continue;
                            }

                            // RS0026: Symbol '{0}' violates the backcompat requirement: 'Do not add multiple overloads with optional parameters'. See '{1}' for details.
                            var overloadHasOptionalParams = overload.HasOptionalParameters();
                            if (overloadHasOptionalParams)
                            {
                                // Flag only if 'method' is a new unshipped API with optional parameters.
                                if (!isMethodShippedApi)
                                {
                                    string errorMessageName = GetErrorMessageName(method, isImplicitlyDeclaredConstructor);
                                    reportDiagnosticAtLocations(AvoidMultipleOverloadsWithOptionalParameters, ImmutableDictionary <string, string> .Empty, errorMessageName, AvoidMultipleOverloadsWithOptionalParameters.HelpLinkUri);
                                    break;
                                }
                            }

                            // RS0027: Symbol '{0}' violates the backcompat requirement: 'Public API with optional parameter(s) should have the most parameters amongst its public overloads'. See '{1}' for details.
                            if (method.Parameters.Length <= overload.Parameters.Length)
                            {
                                // 'method' is unshipped: Flag regardless of whether the overload is shipped/unshipped.
                                // 'method' is shipped:   Flag only if overload is unshipped and has no optional parameters (overload will already be flagged with RS0026)
                                if (!isMethodShippedApi)
                                {
                                    string errorMessageName = GetErrorMessageName(method, isImplicitlyDeclaredConstructor);
                                    reportDiagnosticAtLocations(OverloadWithOptionalParametersShouldHaveMostParameters, ImmutableDictionary <string, string> .Empty, errorMessageName, OverloadWithOptionalParametersShouldHaveMostParameters.HelpLinkUri);
                                    break;
                                }
                                else if (!overloadHasOptionalParams)
                                {
                                    var overloadPublicApiName = GetPublicApiName(overload);
                                    var isOverloadUnshipped   = !lookupPublicApi(overloadPublicApiName, out ApiLine overloadPublicApiLine) ||
                                                                !overloadPublicApiLine.IsShippedApi;
                                    if (isOverloadUnshipped)
                                    {
                                        string errorMessageName = GetErrorMessageName(method, isImplicitlyDeclaredConstructor);
                                        reportDiagnosticAtLocations(OverloadWithOptionalParametersShouldHaveMostParameters, ImmutableDictionary <string, string> .Empty, errorMessageName, OverloadWithOptionalParametersShouldHaveMostParameters.HelpLinkUri);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }

                return;

                // local functions
                void reportDiagnosticAtLocations(DiagnosticDescriptor descriptor, ImmutableDictionary <string, string> propertyBag, params object[] args)
                {
                    foreach (var location in locationsToReport)
                    {
                        reportDiagnostic(Diagnostic.Create(descriptor, location, propertyBag, args));
                    }
                }

                void reportDeclareNewApi(ISymbol symbol, bool isImplicitlyDeclaredConstructor, string publicApiName)
                {
                    // TODO: workaround for https://github.com/dotnet/wpf/issues/2690
                    if (publicApiName == "XamlGeneratedNamespace.GeneratedInternalTypeHelper" ||
                        publicApiName == "XamlGeneratedNamespace.GeneratedInternalTypeHelper.GeneratedInternalTypeHelper() -> void")
                    {
                        return;
                    }

                    // Unshipped public API with no entry in public API file - report diagnostic.
                    string errorMessageName = GetErrorMessageName(symbol, isImplicitlyDeclaredConstructor);
                    // Compute public API names for any stale siblings to remove from unshipped text (e.g. during signature change of unshipped public API).
                    var siblingPublicApiNamesToRemove = GetSiblingNamesToRemoveFromUnshippedText(symbol);
                    ImmutableDictionary <string, string> propertyBag = ImmutableDictionary <string, string> .Empty
                                                                       .Add(PublicApiNamePropertyBagKey, publicApiName)
                                                                       .Add(MinimalNamePropertyBagKey, errorMessageName)
                                                                       .Add(PublicApiNamesOfSiblingsToRemovePropertyBagKey, siblingPublicApiNamesToRemove);

                    reportDiagnosticAtLocations(DeclareNewApiRule, propertyBag, errorMessageName);
                }

                void reportAnnotateApi(ISymbol symbol, bool isImplicitlyDeclaredConstructor, ApiName publicApiName, bool isShipped)
                {
                    // Public API missing annotations in public API file - report diagnostic.
                    string errorMessageName = GetErrorMessageName(symbol, isImplicitlyDeclaredConstructor);
                    ImmutableDictionary <string, string> propertyBag = ImmutableDictionary <string, string> .Empty
                                                                       .Add(PublicApiNamePropertyBagKey, publicApiName.Name)
                                                                       .Add(PublicApiNameWithNullabilityPropertyBagKey, withObliviousIfNeeded(publicApiName.NameWithNullability))
                                                                       .Add(MinimalNamePropertyBagKey, errorMessageName)
                                                                       .Add(PublicApiIsShippedPropertyBagKey, isShipped ? "true" : "false");

                    reportDiagnosticAtLocations(AnnotateApiRule, propertyBag, errorMessageName);
                }

                string withObliviousIfNeeded(string name)
                {
                    return(symbolUsesOblivious ? WithObliviousMarker(name) : name);
                }

                void reportObliviousApi(ISymbol symbol)
                {
                    // Public API using oblivious types in public API file - report diagnostic.
                    string errorMessageName = GetErrorMessageName(symbol, isImplicitlyDeclaredConstructor);

                    reportDiagnosticAtLocations(ObliviousApiRule, ImmutableDictionary <string, string> .Empty, errorMessageName);
                }

                bool lookupPublicApi(ApiName overloadPublicApiName, out ApiLine overloadPublicApiLine)
                {
                    if (_useNullability)
                    {
                        return(_publicApiMap.TryGetValue(overloadPublicApiName.NameWithNullability, out overloadPublicApiLine) ||
                               _publicApiMap.TryGetValue(WithObliviousMarker(overloadPublicApiName.NameWithNullability), out overloadPublicApiLine) ||
                               _publicApiMap.TryGetValue(overloadPublicApiName.Name, out overloadPublicApiLine));
                    }
                    else
                    {
                        return(_publicApiMap.TryGetValue(overloadPublicApiName.Name, out overloadPublicApiLine));
                    }
                }
            }
Ejemplo n.º 18
0
 public static void Log(ApiName apiName, String data, Exception ex, String logType)
 {
     data += "\t[Error Message]: " + ex.Message + "\t[Inner Exception]: " + ex.InnerException + "\t[Stacktrace]: " + ex.StackTrace;
     Log(apiName, data, logType);
 }