From ed99f080311b840bc50c87fbd1c462828929ad3a Mon Sep 17 00:00:00 2001 From: Mikkel Nylander Bundgaard Date: Sat, 8 Dec 2018 01:06:31 +0100 Subject: [PATCH 1/3] Replace String.Format with string interpolation Also added language identifiers to some code blocks in the wcf folder. --- .../data/adonet/asynchronous-programming.md | 2 +- .../windows-applications-using-callbacks.md | 11 +++---- ...updating-data-sources-with-dataadapters.md | 2 +- .../wcf/configuring-wcf-services-in-code.md | 2 +- docs/framework/wcf/diagnostics/wmi/index.md | 3 +- ...ng-applications-using-the-udp-transport.md | 10 +++--- .../how-to-create-a-transactional-service.md | 18 +++++----- .../wcf/migrating-from-net-remoting-to-wcf.md | 17 ++++------ ...tom-message-encoder-custom-text-encoder.md | 3 +- docs/framework/wcf/samples/custom-token.md | 33 ++++++++----------- .../samples/net-tcp-port-sharing-sample.md | 5 ++- .../wcf/samples/supporting-tokens.md | 13 ++++---- .../wcf/services-and-transactions.md | 12 +++---- 13 files changed, 57 insertions(+), 74 deletions(-) diff --git a/docs/framework/data/adonet/asynchronous-programming.md b/docs/framework/data/adonet/asynchronous-programming.md index f8a3cbb22e93e..7fd38596ccaea 100644 --- a/docs/framework/data/adonet/asynchronous-programming.md +++ b/docs/framework/data/adonet/asynchronous-programming.md @@ -123,7 +123,7 @@ class A { SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) - Console.WriteLine(String.Format("{0}", reader[0])); + Console.WriteLine(reader[0]); } } } diff --git a/docs/framework/data/adonet/sql/windows-applications-using-callbacks.md b/docs/framework/data/adonet/sql/windows-applications-using-callbacks.md index 4b8c6f9fc7cdc..3301f8cb25665 100644 --- a/docs/framework/data/adonet/sql/windows-applications-using-callbacks.md +++ b/docs/framework/data/adonet/sql/windows-applications-using-callbacks.md @@ -121,9 +121,7 @@ Imports System.Data.SqlClient Catch ex As Exception isExecuting = False - DisplayStatus( _ - String.Format("Ready (last error: {0})", _ - ex.Message)) + DisplayStatus($"Ready (last error: {ex.Message})") If connection IsNot Nothing Then connection.Close() End If @@ -177,7 +175,7 @@ Imports System.Data.SqlClient ' invoke it, like this: Me.Invoke(New _ DisplayInfoDelegate(AddressOf DisplayStatus), _ - String.Format("Ready(last error: {0}", ex.Message)) + $"Ready(last error: {ex.Message}") Finally isExecuting = False If connection IsNot Nothing Then @@ -295,8 +293,7 @@ private void button1_Click(object sender, System.EventArgs e) catch (Exception ex) { isExecuting = false; - DisplayStatus( - string.Format("Ready (last error: {0})", ex.Message)); + DisplayStatus($"Ready (last error: {ex.Message})"); if (connection != null) { connection.Close(); @@ -352,7 +349,7 @@ private void HandleCallback(IAsyncResult result) // You can create the delegate instance as you // invoke it, like this: this.Invoke(new DisplayInfoDelegate(DisplayStatus), - String.Format("Ready(last error: {0}", ex.Message)); + $"Ready(last error: {ex.Message}"); } finally { diff --git a/docs/framework/data/adonet/updating-data-sources-with-dataadapters.md b/docs/framework/data/adonet/updating-data-sources-with-dataadapters.md index ffd9a976ccc7f..d079434a377f6 100644 --- a/docs/framework/data/adonet/updating-data-sources-with-dataadapters.md +++ b/docs/framework/data/adonet/updating-data-sources-with-dataadapters.md @@ -290,7 +290,7 @@ class Program { String primaryCols = String.Join(",", primaryColumns.Select(col => col.ColumnName)); String resetCols = String.Join(",", resetColumns.Select(col => "Max(" + col.ColumnName + ") as " + col.ColumnName)); - String selectString = String.Format("Select {0},{1} from Course Group by {0}", primaryCols, resetCols); + String selectString = $"Select {primaryCols},{resetCols} from Course Group by {primaryCols}"); SqlCommand selectCommand = new SqlCommand(selectString); diff --git a/docs/framework/wcf/configuring-wcf-services-in-code.md b/docs/framework/wcf/configuring-wcf-services-in-code.md index df4710b93e314..c9440e7710774 100644 --- a/docs/framework/wcf/configuring-wcf-services-in-code.md +++ b/docs/framework/wcf/configuring-wcf-services-in-code.md @@ -32,7 +32,7 @@ public class Service1 : IService1 public string GetData(int value) { - return string.Format("You entered: {0}", value); + return $"You entered: {value}"; } public CompositeType GetDataUsingDataContract(CompositeType composite) diff --git a/docs/framework/wcf/diagnostics/wmi/index.md b/docs/framework/wcf/diagnostics/wmi/index.md index 8444e9350f8bb..2be8a1e3aca0e 100644 --- a/docs/framework/wcf/diagnostics/wmi/index.md +++ b/docs/framework/wcf/diagnostics/wmi/index.md @@ -166,8 +166,7 @@ Whoami /user You can also access remote WMI instances programmatically by using classes provided by the namespace. The following code sample demonstrates how to do this. ```csharp -String wcfNamespace = String.Format(@"\\{0}\Root\ServiceModel", - this.serviceMachineName); +String wcfNamespace = $@"\\{this.serviceMachineName}\Root\ServiceModel"); ConnectionOptions connection = new ConnectionOptions(); connection.Authentication = AuthenticationLevel.PacketPrivacy; diff --git a/docs/framework/wcf/feature-details/creating-multicasting-applications-using-the-udp-transport.md b/docs/framework/wcf/feature-details/creating-multicasting-applications-using-the-udp-transport.md index 9841c8179cc0b..967889acfa405 100644 --- a/docs/framework/wcf/feature-details/creating-multicasting-applications-using-the-udp-transport.md +++ b/docs/framework/wcf/feature-details/creating-multicasting-applications-using-the-udp-transport.md @@ -9,7 +9,7 @@ Multicasting applications send small messages to a large number of recipients at ## Implementing a Multicast Application To implement a multicast application, define a service contract and for each software component that needs to respond to the multicast messages, implement the service contract. For example, a stock ticker application might define a service contract: -``` +```csharp // Shared contracts between the client and the service [ServiceContract] interface IStockTicker @@ -37,7 +37,7 @@ class StockInfo Each application that wants to receive multicast messages must host a service that exposes this interface. For example, here is a code sample that illustrates how to receive multicast messages: -``` +```csharp // Service Address string serviceAddress = "soap.udp://224.0.0.1:40000"; // Binding @@ -57,7 +57,7 @@ Console.ReadLine(); In this type of a scenario it is the client that actually sends out multicast messages. Each service that is listening at the correct UDP address will receive the multicast messages. Here is an example of a client that sends out multicast messages: -``` +```csharp // Multicast Address string serviceAddress = "soap.udp://224.0.0.1:40000"; @@ -76,7 +76,7 @@ while (true) { // This will continue to mulicast stock information proxy.SendStockInfo(GetStockInfo()); - Console.WriteLine(String.Format("sent stock info at {0}", DateTime.Now)); + Console.WriteLine($"sent stock info at {DateTime.Now}"); // Wait for one second before sending another update System.Threading.Thread.Sleep(new TimeSpan(0, 0, 1)); } @@ -90,7 +90,7 @@ while (true) ### Two-way Multicast Messaging While multicast messages are generally one-way, the UdpBinding does support request/reply message exchange. Messages sent using the UDP transport contain both a From and To address. Care must be taken when using the From address as it could be maliciously changed en-route. The address can be checked using the following code: -``` +```csharp if (address.AddressFamily == AddressFamily.InterNetwork) { // IPv4 diff --git a/docs/framework/wcf/feature-details/how-to-create-a-transactional-service.md b/docs/framework/wcf/feature-details/how-to-create-a-transactional-service.md index 94ebdc81e431c..2589ae3d46abb 100644 --- a/docs/framework/wcf/feature-details/how-to-create-a-transactional-service.md +++ b/docs/framework/wcf/feature-details/how-to-create-a-transactional-service.md @@ -10,7 +10,7 @@ This sample demonstrates various aspects of creating a transactional service and 1. Create a service contract and annotate the operations with the desired setting from the enumeration to specify the incoming transaction requirements. Note that you can also place the on the service class being implemented. This allows for a single implementation of an interface to use these transaction settings, instead of every implementation. - ``` + ```csharp [ServiceContract] public interface ICalculator { @@ -27,7 +27,7 @@ This sample demonstrates various aspects of creating a transactional service and 2. Create an implementation class, and use the to optionally specify a and a . You should note that in many cases, the default of 60 seconds and the default of `Unspecified` are appropriate. For each operation, you can use the attribute to specify whether work performed within the method should occur within the scope of a transaction scope according to the value of the attribute. In this case, the transaction used for the `Add` method is the same as the mandatory incoming transaction that is flowed from the client, and the transaction used for the `Subtract` method is either the same as the incoming transaction if one was flowed from the client, or a new implicitly and locally created transaction. - ``` + ```csharp [ServiceBehavior( TransactionIsolationLevel = System.Transactions.IsolationLevel.Serializable, TransactionTimeout = "00:00:45")] @@ -37,7 +37,7 @@ This sample demonstrates various aspects of creating a transactional service and public double Add(double n1, double n2) { // Perform transactional operation - RecordToLog(String.Format("Adding {0} to {1}", n1, n2)); + RecordToLog($"Adding {n1} to {n2}"); return n1 + n2; } @@ -45,7 +45,7 @@ This sample demonstrates various aspects of creating a transactional service and public double Subtract(double n1, double n2) { // Perform transactional operation - RecordToLog(String.Format("Subtracting {0} from {1}", n2, n1)); + RecordToLog($"Subtracting {n2} from {n1}"); return n1 - n2; } @@ -122,7 +122,7 @@ This sample demonstrates various aspects of creating a transactional service and 1. By default, WCF operations automatically complete transactions if no unhandled exceptions are thrown. You can modify this behavior by using the property and the method. When an operation is required to occur within the same transaction as another operation (for example, a debit and credit operation), you can disable the autocomplete behavior by setting the property to `false` as shown in the following `Debit` operation example. The transaction the `Debit` operation uses is not completed until a method with the property set to `true` is called, as shown in the operation `Credit1`, or when the method is called to explicitly mark the transaction as complete, as shown in the operation `Credit2`. Note that the two credit operations are shown for illustration purposes, and that a single credit operation would be more typical. - ``` + ```csharp [ServiceBehavior] public class CalculatorService : IAccount { @@ -158,7 +158,7 @@ This sample demonstrates various aspects of creating a transactional service and 2. For the purposes of transaction correlation, setting the property to `false` requires the use of a sessionful binding. This requirement is specified with the `SessionMode` property on the . - ``` + ```csharp [ServiceContract(SessionMode = SessionMode.Required)] public interface IAccount { @@ -178,7 +178,7 @@ This sample demonstrates various aspects of creating a transactional service and 1. WCF uses the property to specify whether the underlying service instance is released when a transaction completes. Since this defaults to `true`, unless configured otherwise, WCF exhibits an efficient and predictable "just-in-time" activation behavior. Calls to a service on a subsequent transaction are assured a new service instance with no remnants of the previous transaction's state. While this is often useful, sometimes you may want to maintain state within the service instance beyond the transaction completion. Examples of this would be when required state or handles to resources are expensive to retrieve or reconstitute. You can do this by setting the property to `false`. With that setting, the instance and any associated state will be available on subsequent calls. When using this, give careful consideration to when and how state and transactions will be cleared and completed. The following sample demonstrates how to do this by maintaining the instance with the `runningTotal` variable. - ``` + ```csharp [ServiceBehavior(TransactionIsolationLevel = [ServiceBehavior( ReleaseServiceInstanceOnTransactionComplete = false)] public class CalculatorService : ICalculator @@ -189,7 +189,7 @@ This sample demonstrates various aspects of creating a transactional service and public double Add(double n) { // Perform transactional operation - RecordToLog(String.Format("Adding {0} to {1}", n, runningTotal)); + RecordToLog($"Adding {n} to {runningTotal}"); runningTotal = runningTotal + n; return runningTotal; } @@ -198,7 +198,7 @@ This sample demonstrates various aspects of creating a transactional service and public double Subtract(double n) { // Perform transactional operation - RecordToLog(String.Format("Subtracting {0} from {1}", n, runningTotal)); + RecordToLog($"Subtracting {n} from {runningTotal}"); runningTotal = runningTotal - n; return runningTotal; } diff --git a/docs/framework/wcf/migrating-from-net-remoting-to-wcf.md b/docs/framework/wcf/migrating-from-net-remoting-to-wcf.md index c69ee35af6b6b..4a0bab7b46c44 100644 --- a/docs/framework/wcf/migrating-from-net-remoting-to-wcf.md +++ b/docs/framework/wcf/migrating-from-net-remoting-to-wcf.md @@ -83,8 +83,7 @@ using (ServiceHost serviceHost = new ServiceHost(typeof(WCFServer), baseAddress) serviceHost.AddServiceEndpoint(typeof(IWCFServer), binding, baseAddress); serviceHost.Open(); - Console.WriteLine(String.Format("The WCF server is ready at {0}.", - baseAddress)); + Console.WriteLine($"The WCF server is ready at {baseAddress}."); Console.WriteLine("Press to terminate service..."); Console.WriteLine(); Console.ReadLine(); @@ -115,8 +114,7 @@ RemotingServer server = (RemotingServer)Activator.GetObject( "tcp://localhost:8080/RemotingServer"); RemotingCustomer customer = server.GetCustomer(42); -Console.WriteLine(String.Format("Customer {0} {1} received.", - customer.FirstName, customer.LastName)); +Console.WriteLine($"Customer {customer.FirstName} {customer.LastName} received."); ``` The RemotingServer instance returned from Activator.GetObject() is known as a "transparent proxy." It implements the public API for the RemotingServer type on the client, but all the methods call the server object running in a different process or machine. @@ -133,8 +131,7 @@ ChannelFactory channelFactory = IWCFServer server = channelFactory.CreateChannel(); Customer customer = server.GetCustomer(42); -Console.WriteLine(String.Format(" Customer {0} {1} received.", - customer.FirstName, customer.LastName)); +Console.WriteLine($" Customer {customer.FirstName} {customer.LastName} received."); ``` This example shows programming at the channel level because it is most similar to the Remoting example. Also available is the **Add Service Reference** approach in Visual Studio that generates code to simplify client programming. For more information, see the following topics: @@ -263,8 +260,7 @@ try } catch (FaultException fault) { - Console.WriteLine(String.Format("Fault received: {0}", - fault.Detail.ErrorMessage)); + Console.WriteLine($"Fault received: {fault.Detail.ErrorMessage}"); } ``` @@ -445,8 +441,7 @@ public class RemotingServer : MarshalByRefObject new ChannelFactory("customerservice"); ICustomerService service = factory.CreateChannel(); Customer customer = service.GetCustomer(42); - Console.WriteLine(String.Format(" Customer {0} {1} received.", - customer.FirstName, customer.LastName)); + Console.WriteLine($" Customer {customer.FirstName} {customer.LastName} received."); ``` Objects returned by WCF from the server to the client are always by value. The objects are deserialized copies of the data sent by the server. The client can call methods on these local copies without any danger of invoking server code through callbacks. @@ -651,7 +646,7 @@ public class RemotingServer : MarshalByRefObject CustomerId = 43, AccountId = 99}; bool success = service.UpdateCustomer(customer); - Console.WriteLine(String.Format(" Server returned {0}.", success)); + Console.WriteLine($" Server returned {success}."); ``` The customer object will be serialized, and sent to the server, where it is deserialized into a new copy of that object. diff --git a/docs/framework/wcf/samples/custom-message-encoder-custom-text-encoder.md b/docs/framework/wcf/samples/custom-message-encoder-custom-text-encoder.md index 1dd1c527cdbc8..c494eb2b51c7e 100644 --- a/docs/framework/wcf/samples/custom-message-encoder-custom-text-encoder.md +++ b/docs/framework/wcf/samples/custom-message-encoder-custom-text-encoder.md @@ -59,8 +59,7 @@ public class CustomTextMessageEncoder : MessageEncoder this.writerSettings = new XmlWriterSettings(); this.writerSettings.Encoding = Encoding.GetEncoding(factory.CharSet); - this.contentType = string.Format("{0}; charset={1}", - this.factory.MediaType, this.writerSettings.Encoding.HeaderName); + this.contentType = $"{this.factory.MediaType}; charset={this.writerSettings.Encoding.HeaderName}"; } public override string ContentType diff --git a/docs/framework/wcf/samples/custom-token.md b/docs/framework/wcf/samples/custom-token.md index 89ee219bb2cc0..ac14a8ea47ea9 100644 --- a/docs/framework/wcf/samples/custom-token.md +++ b/docs/framework/wcf/samples/custom-token.md @@ -22,7 +22,7 @@ This sample demonstrates how to add a custom token implementation into a Windows ## Client Authentication Using a Custom Security Token The service exposes a single endpoint that is programmatically created using `BindingHelper` and `EchoServiceHost` classes. The endpoint consists of an address, a binding, and a contract. The binding is configured with a custom binding using `SymmetricSecurityBindingElement` and `HttpTransportBindingElement`. This sample sets the `SymmetricSecurityBindingElement` to use a service's X.509 certificate to protect the symmetric key during transmission and to pass a custom `CreditCardToken` in a WS-Security message header as a signed and encrypted security token. The behavior specifies the service credentials that are to be used for client authentication and also information about the service X.509 certificate. -``` +```csharp public static class BindingHelper { public static Binding CreateCreditCardBinding() @@ -43,7 +43,7 @@ public static class BindingHelper To consume a credit card token in the message, the sample uses custom service credentials to provide this functionality. The service credentials class is located in the `CreditCardServiceCredentials` class and is added to the behaviors collections of the service host in the `EchoServiceHost.InitializeRuntime` method. -``` +```csharp class EchoServiceHost : ServiceHost { string creditCardFile; @@ -58,7 +58,6 @@ class EchoServiceHost : ServiceHost } creditCardFile = String.Format("{0}\\{1}", System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath, creditCardFile); - } override protected void InitializeRuntime() @@ -80,13 +79,12 @@ class EchoServiceHost : ServiceHost The client endpoint is configured in a similar manner as the service endpoint. The client uses the same `BindingHelper` class to create a binding. The rest of the setup is located in the `Client` class. The client also sets information to be contained in the `CreditCardToken` and information about the service X.509 certificate in the setup code by adding a `CreditCardClientCredentials` instance with the proper data to the client endpoint behaviors collection. The sample uses X.509 certificate with subject name set to `CN=localhost` as the service certificate. -``` +```csharp Binding creditCardBinding = BindingHelper.CreateCreditCardBinding(); EndpointAddress serviceAddress = new EndpointAddress("http://localhost/servicemodelsamples/service.svc"); // Create a client with given client endpoint configuration -channelFactory = -new ChannelFactory(creditCardBinding, serviceAddress); +channelFactory = new ChannelFactory(creditCardBinding, serviceAddress); // configure the credit card credentials on the channel factory CreditCardClientCredentials credentials = @@ -113,7 +111,7 @@ channelFactory.Close(); The next section describes what must be done to enable a custom token to be transmitted over the wire and consumed by a WCF endpoint. -``` +```csharp class CreditCardToken : SecurityToken { CreditCardInfo cardInfo; @@ -155,7 +153,7 @@ class CreditCardToken : SecurityToken On the client, the `CreditCardSecurityTokenSerializer` class writes the information contained in the security token object representation into the XML writer. -``` +```csharp public class CreditCardSecurityTokenSerializer : WSSecurityTokenSerializer { public CreditCardSecurityTokenSerializer(SecurityTokenVersion version) : base() { } @@ -251,7 +249,7 @@ public class CreditCardSecurityTokenSerializer : WSSecurityTokenSerializer On the service, the functionality resides in the `CreditCardServiceCredentials`, `CreditCardServiceCredentialsSecurityTokenManager`, `CreditCardTokenAuthenticator` and `CreditCardTokenAuthorizationPolicy` classes. -``` +```csharp public class CreditCardClientCredentials : ClientCredentials { CreditCardInfo creditCardInfo; @@ -281,7 +279,7 @@ public class CreditCardSecurityTokenSerializer : WSSecurityTokenSerializer } } -public class CreditCardClientCredentialsSecurityTokenManager : ClientCredentialsSecurityTokenManager + public class CreditCardClientCredentialsSecurityTokenManager : ClientCredentialsSecurityTokenManager { CreditCardClientCredentials creditCardClientCredentials; @@ -336,7 +334,7 @@ public class CreditCardClientCredentialsSecurityTokenManager : ClientCredentials } } -public class CreditCardServiceCredentials : ServiceCredentials + public class CreditCardServiceCredentials : ServiceCredentials { string creditCardFile; @@ -365,8 +363,8 @@ public class CreditCardServiceCredentials : ServiceCredentials } } -public class CreditCardServiceCredentialsSecurityTokenManager : ServiceCredentialsSecurityTokenManager -{ + public class CreditCardServiceCredentialsSecurityTokenManager : ServiceCredentialsSecurityTokenManager + { CreditCardServiceCredentials creditCardServiceCredentials; public CreditCardServiceCredentialsSecurityTokenManager(CreditCardServiceCredentials creditCardServiceCredentials) @@ -496,12 +494,11 @@ public class CreditCardServiceCredentialsSecurityTokenManager : ServiceCredentia ## Displaying the Callers' Information To display the caller's information, use the `ServiceSecurityContext.Current.AuthorizationContext.ClaimSets` as shown in the following sample code. The `ServiceSecurityContext.Current.AuthorizationContext.ClaimSets` contains authorization claims associated with the current caller. The claims are supplied by the `CreditCardToken` class in its `AuthorizationPolicies` collection. -``` +```csharp bool TryGetStringClaimValue(ClaimSet claimSet, string claimType, out string claimValue) { claimValue = null; - IEnumerable matchingClaims = claimSet.FindClaims(claimType, - Rights.PossessProperty); + IEnumerable matchingClaims = claimSet.FindClaims(claimType, Rights.PossessProperty); if (matchingClaims == null) return false; IEnumerator enumerator = matchingClaims.GetEnumerator(); @@ -526,9 +523,7 @@ string GetCallerCreditCardNumber() { issuer = "Unknown"; } - return String.Format( - "Credit card '{0}' issued by '{1}'", - creditCardNumber, issuer); + return $"Credit card '{creditCardNumber}' issued by '{issuer}'"; } } return "Credit card is not known"; diff --git a/docs/framework/wcf/samples/net-tcp-port-sharing-sample.md b/docs/framework/wcf/samples/net-tcp-port-sharing-sample.md index 831aa662186cd..cb01c604ede87 100644 --- a/docs/framework/wcf/samples/net-tcp-port-sharing-sample.md +++ b/docs/framework/wcf/samples/net-tcp-port-sharing-sample.md @@ -38,8 +38,7 @@ binding.PortSharingEnabled = true; // Start a service on a fixed TCP port ServiceHost host = new ServiceHost(typeof(CalculatorService)); ushort salt = (ushort)new Random().Next(); -string address = - String.Format("net.tcp://localhost:9000/calculator/{0}", salt); +string address = $"net.tcp://localhost:9000/calculator/{salt}"; host.AddServiceEndpoint(typeof(ICalculator), binding, address); host.Open(); ``` @@ -60,7 +59,7 @@ class client { Console.Write("Enter the service number to test: "); ushort salt = ushort.Parse(Console.ReadLine()); - string address = String.Format("net.tcp://localhost:9000/calculator/{0}", salt); + string address = $"net.tcp://localhost:9000/calculator/{salt}"; ChannelFactory factory = new ChannelFactory(new NetTcpBinding()); ICalculator proxy = factory.CreateChannel(new EndpointAddress(address)); diff --git a/docs/framework/wcf/samples/supporting-tokens.md b/docs/framework/wcf/samples/supporting-tokens.md index d4263a5b0db7a..ba57f603aab4f 100644 --- a/docs/framework/wcf/samples/supporting-tokens.md +++ b/docs/framework/wcf/samples/supporting-tokens.md @@ -21,7 +21,7 @@ The Supporting Tokens sample demonstrates how to add additional tokens to a mess ## Client Authenticates with Username Token and Supporting X.509 Security Token The service exposes a single endpoint for communicating that is programmatically created using the `BindingHelper` and `EchoServiceHost` classes. The endpoint consists of an address, a binding, and a contract. The binding is configured with a custom binding using `SymmetricSecurityBindingElement` and `HttpTransportBindingElement`. This sample sets the `SymmetricSecurityBindingElement` to use a service X.509 certificate to protect the symmetric key during transmission and to pass a `UserNameToken` along with the supporting `X509SecurityToken` in a WS-Security message header. The symmetric key is used to encrypt the message body and the username security token. The supporting token is passed as an additional binary security token in the WS-Security message header. The authenticity of the supporting token is proved by signing part of the message with the private key associated with the supporting X.509 security token. -``` +```csharp public static Binding CreateMultiFactorAuthenticationBinding() { HttpTransportBindingElement httpTransport = new HttpTransportBindingElement(); @@ -49,7 +49,7 @@ public static Binding CreateMultiFactorAuthenticationBinding() The behavior specifies the service credentials that are to be used for client authentication and also information about the service X.509 certificate. The sample uses `CN=localhost` as a subject name in the service X.509 certificate. -``` +```csharp override protected void InitializeRuntime() { // Extract the ServiceCredentials behavior or create one. @@ -82,7 +82,7 @@ This setting is less secure than the default, ChainTrust. The security implicati Service code: -``` +```csharp [ServiceBehavior(IncludeExceptionDetailInFaults = true)] public class EchoService : IEchoService { @@ -94,8 +94,7 @@ public class EchoService : IEchoService OperationContext.Current.ServiceSecurityContext, out userName, out certificateSubjectName); - return String.Format("Hello {0}, {1}", - userName, certificateSubjectName); + return $"Hello {userName}, {certificateSubjectName}"; } public void Dispose() @@ -168,7 +167,7 @@ public class EchoService : IEchoService The client endpoint is configured in a similar way to the service endpoint. The client uses the same `BindingHelper` class to create a binding. The rest of the setup is located in `Client` class. The client sets information about the user name security token, the supporting X.509 security token and information about the service X.509 certificate in the setup code to the client endpoint behaviors collection. -``` +```csharp static void Main() { // Create the custom binding and an endpoint address for @@ -279,7 +278,7 @@ public class EchoService : IEchoService ## Displaying Callers' Information To display the caller's information, you can use the `ServiceSecurityContext.Current.AuthorizationContext.ClaimSets` as shown in the following code. The `ServiceSecurityContext.Current.AuthorizationContext.ClaimSets` contains authorization claims associated with the current caller. Those claims are supplied automatically by Windows Communication Foundation (WCF) for every token received in the message. -``` +```csharp bool TryGetClaimValue(ClaimSet claimSet, string claimType, out TClaimResource resourceValue) where TClaimResource : class diff --git a/docs/framework/wcf/services-and-transactions.md b/docs/framework/wcf/services-and-transactions.md index acdb43b04050e..37a27de8ca721 100644 --- a/docs/framework/wcf/services-and-transactions.md +++ b/docs/framework/wcf/services-and-transactions.md @@ -14,7 +14,7 @@ Windows Communication Foundation (WCF) applications can initiate a transaction f The following sample demonstrates usage of the and attributes to control service-side transaction behavior. -``` +```csharp [ServiceBehavior(TransactionIsolationLevel = System.Transactions.IsolationLevel.Serializable)] public class CalculatorService: ICalculatorLog { @@ -22,7 +22,7 @@ public class CalculatorService: ICalculatorLog TransactionAutoComplete = true)] public double Add(double n1, double n2) { - recordToLog(String.Format("Added {0} to {1}", n1, n2)); + recordToLog($"Added {n1} to {n2}"); return n1 + n2; } @@ -30,7 +30,7 @@ public class CalculatorService: ICalculatorLog TransactionAutoComplete = true)] public double Subtract(double n1, double n2) { - recordToLog(String.Format("Subtracted {0} from {1}", n1, n2)); + recordToLog($"Subtracted {n1} from {n2}"); return n1 - n2; } @@ -38,7 +38,7 @@ public class CalculatorService: ICalculatorLog TransactionAutoComplete = true)] public double Multiply(double n1, double n2) { - recordToLog(String.Format("Multiplied {0} by {1}", n1, n2)); + recordToLog($"Multiplied {n1} by {n2}"); return n1 * n2; } @@ -46,7 +46,7 @@ public class CalculatorService: ICalculatorLog TransactionAutoComplete = true)] public double Divide(double n1, double n2) { - recordToLog(String.Format("Divided {0} by {1}", n1, n2)); + recordToLog($"Divided {n1} by {n2}", n1, n2); return n1 / n2; } @@ -74,7 +74,7 @@ public class CalculatorService: ICalculatorLog Clients can begin a transaction by creating a and invoking service operations within the scope of the transaction. -``` +```csharp using (TransactionScope ts = new TransactionScope(TransactionScopeOption.RequiresNew)) { //Do work here From 1a2e65e7016385e0dae6f3625c3f62378ffaae90 Mon Sep 17 00:00:00 2001 From: Mikkel Nylander Bundgaard Date: Sat, 8 Dec 2018 01:16:27 +0100 Subject: [PATCH 2/3] Add unsaved files --- .../feature-details/wcf-web-http-formatting.md | 16 ++++++++-------- .../wcf/samples/datacontractserializer-sample.md | 3 +-- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/docs/framework/wcf/feature-details/wcf-web-http-formatting.md b/docs/framework/wcf/feature-details/wcf-web-http-formatting.md index b4de80b0ac6ff..5e8f61052c36e 100644 --- a/docs/framework/wcf/feature-details/wcf-web-http-formatting.md +++ b/docs/framework/wcf/feature-details/wcf-web-http-formatting.md @@ -95,22 +95,22 @@ public class Service : IService [WebGet] public string EchoWithGet(string s) { - // if a format query string parameter has been specified, set the response format to that. If no such - // query string parameter exists the Accept header will be used + // if a format query string parameter has been specified, set the response format to that. If no such + // query string parameter exists the Accept header will be used string formatQueryStringValue = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["format"]; if (!string.IsNullOrEmpty(formatQueryStringValue)) { - if (formatQueryStringValue.Equals("xml", System.StringComparison.OrdinalIgnoreCase)) - { - WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Xml; - } - else if (formatQueryStringValue.Equals("json", System.StringComparison.OrdinalIgnoreCase)) + if (formatQueryStringValue.Equals("xml", System.StringComparison.OrdinalIgnoreCase)) + { + WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Xml; + } + else if (formatQueryStringValue.Equals("json", System.StringComparison.OrdinalIgnoreCase)) { WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json; } else { - throw new WebFaultException(string.Format("Unsupported format '{0}'", formatQueryStringValue), HttpStatusCode.BadRequest); + throw new WebFaultException($"Unsupported format '{formatQueryStringValue}'", HttpStatusCode.BadRequest); } } return "You said " + s; diff --git a/docs/framework/wcf/samples/datacontractserializer-sample.md b/docs/framework/wcf/samples/datacontractserializer-sample.md index 7c9922a509e27..5fd4abffdcc85 100644 --- a/docs/framework/wcf/samples/datacontractserializer-sample.md +++ b/docs/framework/wcf/samples/datacontractserializer-sample.md @@ -60,8 +60,7 @@ internal class Record public override string ToString() { - return string.Format("Record: {0} {1} {2} = {3}", n1, - operation, n2, result); + return $"Record: {n1} {operation} {n2} = {result}"; } } ``` From b0611aa2b92f4d50e3542c2cb1f30839bffc2976 Mon Sep 17 00:00:00 2001 From: Mikkel Nylander Bundgaard Date: Sat, 8 Dec 2018 19:32:37 +0100 Subject: [PATCH 3/3] Corrections from review Add space and use interpolation instead of concatenation. --- .../data/adonet/sql/windows-applications-using-callbacks.md | 4 ++-- .../data/adonet/updating-data-sources-with-dataadapters.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/framework/data/adonet/sql/windows-applications-using-callbacks.md b/docs/framework/data/adonet/sql/windows-applications-using-callbacks.md index 3301f8cb25665..a72759492db67 100644 --- a/docs/framework/data/adonet/sql/windows-applications-using-callbacks.md +++ b/docs/framework/data/adonet/sql/windows-applications-using-callbacks.md @@ -175,7 +175,7 @@ Imports System.Data.SqlClient ' invoke it, like this: Me.Invoke(New _ DisplayInfoDelegate(AddressOf DisplayStatus), _ - $"Ready(last error: {ex.Message}") + $"Ready (last error: {ex.Message}") Finally isExecuting = False If connection IsNot Nothing Then @@ -349,7 +349,7 @@ private void HandleCallback(IAsyncResult result) // You can create the delegate instance as you // invoke it, like this: this.Invoke(new DisplayInfoDelegate(DisplayStatus), - $"Ready(last error: {ex.Message}"); + $"Ready (last error: {ex.Message}"); } finally { diff --git a/docs/framework/data/adonet/updating-data-sources-with-dataadapters.md b/docs/framework/data/adonet/updating-data-sources-with-dataadapters.md index d079434a377f6..1d9d902731726 100644 --- a/docs/framework/data/adonet/updating-data-sources-with-dataadapters.md +++ b/docs/framework/data/adonet/updating-data-sources-with-dataadapters.md @@ -288,7 +288,7 @@ class Program { // Build the query string String primaryCols = String.Join(",", primaryColumns.Select(col => col.ColumnName)); - String resetCols = String.Join(",", resetColumns.Select(col => "Max(" + col.ColumnName + ") as " + col.ColumnName)); + String resetCols = String.Join(",", resetColumns.Select(col => $"Max({col.ColumnName}) as {col.ColumnName}")); String selectString = $"Select {primaryCols},{resetCols} from Course Group by {primaryCols}");