# C# Exam Questions 70-483 Reading - Widget - Part 2 ###### tags: `C#` `70-483` `Exam Questions` https://www.briefmenow.org/microsoft/category/exam-70-483-programming-in-c-update-july-21th-2017/page/23/ https://www.examtopics.com/exams/microsoft/70-483/ * [Link Part 1](https://hackmd.io/@sfRJH1u7S464tSaizL7ZsQ/SJSWTKB3w) --- page 12 https://www.briefmenow.org/microsoft/which-code-should-you-insert-at-line-28-13/ https://www.briefmenow.org/microsoft/which-code-should-you-insert-at-line-28-14/ ``` public class Program { private static System.Diagnostics.Stopwatch _execTimer = new System.Diagnostics.Stopwatch(); public static void Delay(int delay) { Thread.Sleep(delay); } public static void LogLongExecDelay(string msg) { if(_execTimer.Elapsed.Seconds >= 5) { throw new Exception(string.Format("Excecution is too long > {0} > {1}", msg, _execTimer.Elapsed.TotalMilliseconds)); } } public static void Main() { _execTimer.Start(); try { Delay(10); LogLongExecDelay("Delay{10}") Delay(5000); LogLongExecDelay("Delay{5000}") } catch (Exception ex) { [] } } } ``` You need to ensure that if an exception occurs, the exception will be logged. Which code should you insert at line 28? https://www.briefmenow.org/microsoft/you-need-to-ensure-that-after-proc1-executes-the-datab/ --- # TryParse() ## 1. DateTime.TryParse() You are developing an application that accepts the input of dates from the user. Users enter the date in their local format. The date entered by the user is stored in a ``string`` variable named ``inputDate``. The valid date value must be placed in a ``DateTime`` variable named ``validatedDate``. You need to validate the entered date and convert it to Coordinated Universal Time (UTC). The code must not cause an exception to be thrown. Which code segment should you use? ``AdjustToUniversal`` parses s and, if necessary, converts it to UTC. Note: The ``DateTime.TryParse`` method converts the specified ``string`` representation of a date and time to its ``DateTime`` equivalent using the specified culture-specific format information and formatting style, and returns a value that indicates whether the conversion succeeded. ``` bool validDate = DateTime.TryParse( inputDate, CultureInfo.CurrentCalture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeLocal, out validatedDate) ``` --- ### [DateTime.TryParse()](https://docs.microsoft.com/zh-tw/dotnet/api/system.datetime.tryparse?view=netcore-3.1) e.g., ``` string[] dateStrings = {"05/01/2009 14:57:32.8", "2009-05-01 14:57:32.8", "2009-05-01T14:57:32.8375298-04:00", "5/01/2008", "5/01/2008 14:57:32.80 -07:00", "1 May 2008 2:57:32.8 PM", "16-05-2009 1:00:32 PM", "Fri, 15 May 2009 20:10:57 GMT" }; DateTime dateValue; Console.WriteLine("Attempting to parse strings using {0} culture.", CultureInfo.CurrentCulture.Name); foreach (string dateString in dateStrings) { if (DateTime.TryParse(dateString, out dateValue)) { Console.WriteLine(" Converted '{0}' to {1} ({2}).", dateString, dateValue, dateValue.Kind); } else { Console.WriteLine(" Unable to parse '{0}'.", dateString); } } ``` ``` DateTime.TryParse(String, IFormatProvider, DateTimeStyles, DateTime) ``` --- ## 2. int.TryParse / Int32.TryParse ### https://www.briefmenow.org/microsoft/which-code-segment-should-you-add-at-line-19-8/ You are developing an application that includes the following code segment. ``` using System; class MainClass { public static void Main(string[] args) { bool bValidInteger = false; int value = 0; do { Console.WriteLine("Enter an integer: "); bValidInteger = GetValidInteger(ref value); } while (!bValidInteger); Console.WriteLine("You entered a valid integer, " + value); } public static bool GetValidInteger(ref int val) { string sLine = Console.WriteLine(); int number; { return false; } else { val = number; return true; } } } ``` You need to ensure that the application accepts only integer input and prompts the user each time non-integer input is entered. Which code segment should you add at line 19? A. ``If (!int.TryParse(sLine, out number))`` B. ``If ((number = Int32.Parse(sLine)) == Single.NaN)`` C. ``If ((number = int.Parse(sLine)) > Int32.MaxValue)`` D. ``If (Int32.TryParse(sLine, out number))`` Answer: A ### [int.TryParse(myStr, out a)](https://www.tutorialspoint.com/chash-int-tryparse-method) Convert a ``string`` representation of number to an ``integer``, using the ``int.TryParse`` method in C#. If the ``string`` cannot be converted, then the ``int.TryParse`` method returns ``false`` i.e. a Boolean value. Let’s say you have a string representation of a number. ``` string myStr = "12"; ``` Now to convert it to an ``integer``, use the ``int.TryParse()``. It will get converted and will return ``True``. ``` bool result = int.TryParse(myStr, out a); ``` ### [Int32.TryParse Method](https://docs.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=netcore-3.1) --- # Assembly ## 1 You are developing an application by using C#. The application includes an object that performs a long running process. You need to ensure that the garbage collector does not release the object’s resources until the process completes. Which garbage collector method should you use? A. ``ReRegisterForFinalize()`` Requests that the system call the finalizer for the specified object for which SuppressFinalize(Object) has previously been called. B. ``SuppressFinalize()`` Requests that the common language runtime not call the finalizer for the specified object. C. ``Collect()`` Forces an immediate garbage collection of all generations. D. ``WaitForFullGCApproach()`` Returns the status of a registered notification for determining whether a full, blocking garbage collection by the common language runtime is imminent. Answer: B --- ## 2 You are creating a console application by using C#. You need to __access the application assembly__. Which code segment should you use? ``` Assembly.GetExecutingAssembly(); ``` * Assembly.GetExecutingAssembly: Gets the assembly that contains the code that is currently executing. http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getexecutingassembly(v=vs.110).aspx * Assembly.GetAssembly: Gets the currently loaded assembly in which the specified class is defined. http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getassembly.aspx --- ## 3 You are developing an application by using C#. You provide a public key to the development team during development. You need to specify that the assembly is not fully signed when it is built. Which two assembly attributes should you include in the source code? (Each correct answer presents part of the solution. Choose two.) C. ``AssemblyDelaySignAttribute`` D. ``AssemblyKeyFileAttribute`` Explanation: http://msdn.microsoft.com/en-us/library/t07a3dye(v=vs.110).aspx --- ## 4 You are developing an assembly that will be used by multiple applications. You need to install the assembly in the Global Assembly Cache (GAC). Which two actions can you perform to achieve this goal? (Each correct answer presents a complete solution. Choose two.) A. Use the Assembly Registration tool (regasm.exe) to register the assembly and to copy the assembly to the GAC. B. Use the Strong Name tool (sn.exe) to copy the assembly into the GAC. C. Use Microsoft Register Server (regsvr32.exe) to add the assembly to the GAC. D. Use the Global Assembly Cache tool (gacutil.exe) to add the assembly to the GAC. E. Use Windows Installer 2.0 to add the assembly to the GAC. --- Answer: Use the Global Assembly Cache tool (gacutil.exe) to add the assembly to the GAC. Use Windows Installer 2.0 to add the assembly to the GAC. --- There are two ways to deploy an assembly into the global assembly cache: * Use an __installer__ designed to work with the __global assembly cache__. This is the preferred option for installing assemblies into the global assembly cache. * Use a __developer tool__ called the __Global Assembly Cache tool (Gacutil.exe), provided by the Windows Software Development Kit (SDK)__. Note: In deployment scenarios, use __Windows Installer 2.0__ to install assemblies into the global assembly cache. Use the __Global Assembly Cache tool__ only in development scenarios, because it does not provide assembly reference counting and other features provided when using the Windows Installer. ### [Global Assembly Cache](http://msdn.microsoft.com/en-us/library/yf1d93sz%28v=vs.110%29.aspx) --- ## 5. https://www.briefmenow.org/microsoft/you-need-to-ensure-that-the-class-library-assembly-is-s-2/ You are creating a class library that will be used in a web application. You need to ensure that the class library assembly __is strongly named__. What should you do? A. Use the gacutil.exe command-line tool. B. Use the xsd.exe command-line tool. C. Use the aspnet_regiis.exe command-line tool. D. Use assembly attributes. Answer: D The Windows Software Development Kit (SDK) provides several ways to sign an assembly with a strong name: * Using the Assembly Linker (Al.exe) provided by the Windows SDK. * Using assembly attributes to insert the strong name information in your code. You can use either the ``AssemblyKeyFileAttribute`` or the ``AssemblyKeyNameAttribute``, depending on where the key file to be used is located. * Using compiler options such ``/keyfile`` or ``/delaysign`` in C# and Visual Basic, or the ``/KEYFILE`` or ``/DELAYSIGN`` linker option in C++. (For information on delay signing, see Delay Signing an Assembly.) Note: * A strong name consists of the assembly’s identity–its simple text name, version number, and culture information (if provided)–plus a public key and a digital signature. It is generated from an assembly file (the file that contains the assembly manifest, which in turn contains the names and hashes of all the files that make up the assembly), using the corresponding private key. Microsoft® Visual Studio® .NET and other development tools provided in the .NET Framework SDK can assign strong names to an assembly. Assemblies with the same strong name are expected to be identical. --- ## 6. https://www.briefmenow.org/microsoft/which-commands-should-you-run-21/ ``` [] -k assemblyKey.snk [] /out:Assembly1.dll /keyfile assemblyKey.snk ``` * ``al.exe`` * ``gacutil.exe`` * ``ildasm.exe`` * ``resgen.exe`` * ``sn.exe`` Answer: ``` sn.exe -k assemblyKey.snk al.exe /out:Assembly1.dll /keyfile assemblyKey.snk ``` --- ## 7. Assembly.LoadFile / Assembly.Load() ### 7.1. https://www.briefmenow.org/microsoft/which-code-segment-should-you-use-1238/ You are creating a console application by using C#. You need to access the assembly found in the file named ``car.dll``. Which code segment should you use? A. ``Assembly.Load();`` B. ``Assembly.GetExecutingAssembly();`` C. ``this.GetType();`` D. ``Assembly.LoadFile("car.dll");`` --- Answer: ``Assembly.LoadFile(“car.dll”);`` ### [``Assembly.LoadFile Method``](https://docs.microsoft.com/en-us/dotnet/api/system.reflection.assembly.loadfile?redirectedfrom=MSDN&view=netcore-3.1) Loads the contents of an assembly file on the specified path. ### [``Assembly.Load()``](https://docs.microsoft.com/en-us/dotnet/api/system.reflection.assembly.load?view=netcore-3.1) * ``Load(Byte[])``: Loads the assembly with a common object file format (COFF)-based image containing an emitted assembly. The assembly is loaded into the application domain of the caller. * ``Load(String)``: Loads an assembly with the specified name. * ``Load(AssemblyName)``: Loads an assembly given its AssemblyName. * ``Load(Byte[], Byte[])``: Loads the assembly with a common object file format (COFF)-based image containing an emitted assembly, optionally including symbols for the assembly. The assembly is loaded into the application domain of the caller. ### [``Assembly.GetExecutingAssembly()``](https://docs.microsoft.com/en-us/dotnet/api/system.reflection.assembly.getexecutingassembly?view=netcore-3.1) The assembly that contains the code that is currently executing. --- ### 7.2 https://www.briefmenow.org/microsoft/which-code-segment-should-you-insert-at-line-04-80/ You are developing code for an application that retrieves information about Microsoft .NET Framework assemblies. The following code segment is part of the application: ``` public void ViewMetadata(string filepath) { var bytes = File.ReadAllBytes(filepath); ... } ``` You need to insert code at line 04. The code __must load the assembly__. Once the assembly is loaded, the code __must be able to read the assembly metadata__, but the code must be __denied access from executing code from the assembly__. Which code segment should you insert at line 04? A. ``Assembly.ReflectionOnlyLoadFrom(bytes);`` B. ``Assembly.ReflectionOniyLoad(bytes);`` C. ``Assembly.Load(bytes);`` D. ``Assembly.LoadFrom(bytes);`` Answer: B --- ### [Assembly.ReflectionOnlyLoadFrom(String) Method](https://docs.microsoft.com/en-us/dotnet/api/system.reflection.assembly.reflectiononlyloadfrom?view=netcore-3.1) * Namespace: ``System.Reflection`` * Loads an assembly into the reflection-only context, given its path. ``` public static System.Reflection.Assembly ReflectionOnlyLoadFrom (string assemblyFile); ``` ### [ReflectionOnlyLoad(Byte[])](https://docs.microsoft.com/en-us/dotnet/api/system.reflection.assembly.reflectiononlyload?redirectedfrom=MSDN&view=netcore-3.1#System_Reflection_Assembly_ReflectionOnlyLoad_System_String_) * Namespace: ``System.Reflection`` * Loads the assembly from a common object file format (COFF)-based image containing an emitted assembly. The assembly is loaded into the reflection-only context of the caller's application domain. ``` public static System.Reflection.Assembly ReflectionOnlyLoad (byte[] rawAssembly); ``` #### Remarks You __cannot execute code from an assembly loaded into the reflection-only context__. To execute code, the assembly must be loaded into the execution context as well, using the ``Load`` method. The reflection-only context is no different from other contexts. Assemblies that are loaded into the context can be unloaded only by unloading the application domain. --- ## 8. https://www.briefmenow.org/microsoft/which-two-assembly-identity-attributes-should-you-inclu-2/ You are developing an application that will be deployed to multiple computers. You set the assembly name. You need to create a unique identity for the application assembly. Which two assembly identity attributes should you include in the source code? A. ``AssemblyTitleAttribute`` B. ``AssemblyCultureAttribute`` C. ``AssemblyVersionAttribute`` D. ``AssemblyKeyNameAttribute`` E. ``AssemblyFileVersion`` Answer: B, C Explanation: The ``AssemblyName`` object contains information about an assembly, which you can use to bind to that assembly. An assembly’s identity consists of the following: * Simple name * Version number * Cryptographic key pairSupported culture B: ``AssemblyCultureAttribute`` Specifies which culture the assembly supports. The attribute is used by compilers to distinguish between a main assembly and a satellite assembly. A main assembly contains code and the neutral culture’s resources. A satellite assembly contains only resources for aparticular culture, as in [assembly:AssemblyCultureAttribute(“de”)] C: ``AssemblyVersionAttribute`` Specifies the version of the assembly being attributed. The assembly version number is part of an assembly’s identity and plays a key part in binding to the assembly and in version policy. --- # Cryptographic hashing algorithm ## 1. Definition ### 1.1. https://www.briefmenow.org/microsoft/which-algorithm-should-you-use-13/ You are developing an application that will transmit large amounts of data between a client computer and a server. You need to __ensure the validity of the data by using a cryptographic hashing algorithm__. Which algorithm should you use? Answer: ``HMACSHA256`` --- * [HashAlgorithm Class](https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.hashalgorithm?view=netcore-3.1) -- Namespace: System.Security.Cryptography -- Assembly: System.Security.Cryptography.Primitives.dll -- Represents the base class from which all implementations of cryptographic hash algorithms must derive. -- Derived: *** System.Security.Cryptography.KeyedHashAlgorithm *** System.Security.Cryptography.MD5 *** System.Security.Cryptography.RIPEMD160 *** System.Security.Cryptography.SHA1 *** System.Security.Cryptography.SHA256 *** System.Security.Cryptography.SHA384 *** System.Security.Cryptography.SHA512 * [Aes Class](https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.aes?view=netcore-3.1) -- Namespace: System.Security.Cryptography -- Represents the abstract base class from which all implementations of the Advanced Encryption Standard (AES) must inherit. * [DES Class](https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.des?view=netcore-3.1) -- Namespace: System.Security.Cryptography -- Represents the base class for the Data Encryption Standard (DES) algorithm from which all DES implementations must derive. * [RNGCryptoServiceProvider Class](https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.rngcryptoserviceprovider?view=netcore-3.1) -- Namespace: System.Security.Cryptography -- Implements a __cryptographic Random Number Generator__ (RNG) using the implementation provided by the cryptographic service provider (CSP). This class cannot be inherited. The .NET Framework provides the following classes that implement hashing algorithms: HMACSHA1. MACTripleDES. MD5CryptoServiceProvider. RIPEMD160. SHA1Managed. SHA256Managed. SHA384Managed. SHA512Managed. HMAC variants of all of the Secure Hash Algorithm (SHA), Message Digest 5 (MD5), and RIPEMD-160 algorithms. CryptoServiceProvider implementations (managed code wrappers) of all the SHA algorithms. Cryptography Next Generation (CNG) implementations of all the MD5 and SHA algorithms. http://msdn.microsoft.com/en-us/library/92f9ye3s.aspx#hash_values --- ### 1.2. https://www.briefmenow.org/microsoft/which-algorithm-should-you-use-14/ You are developing an application that will transmit large amounts of data between a client computer and a server. You need to ensure the validity of the data by using a __cryptographic hashing algorithm__. Which algorithm should you use? A. ECDsa B. RNGCryptoServiceProvider C. Rfc2898DeriveBytes D. HMACSHA512 Answer: ``HMACSHA512`` * [ECDsa Class](https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.ecdsa?view=netcore-3.1) -- Namespace: ``System.Security.Cryptography`` -- Provides an abstract base class that encapsulates the Elliptic Curve __Digital Signature__ Algorithm (ECDSA). * [Rfc2898DeriveBytes Class](https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.rfc2898derivebytes?view=netcore-3.1) -- Namespace: ``System.Security.Cryptography`` -- Implements password-based key derivation functionality, PBKDF2, by using a pseudo-random number generator based on ``HMACSHA1``. --- ### 1.3. https://www.briefmenow.org/microsoft/which-algorithm-should-you-use-15/ You are developing an application that will transmit large amounts of data between a client computer and a server. You need to ensure the validity of the data by using a __cryptographic hashing algorithm__. Which algorithm should you use? A. RSA B. Aes C. HMACSHA256 D. DES Answer: C --- ### 1.4. https://www.briefmenow.org/microsoft/which-algorithmshould-you-use/ You are developing an application that will transmit large amounts of data between a client computer and a server. You need to ensure the validity of the data by using a __cryptographic hashing algorithm__. Which algorithm should you use? A. RSA B. HMACSHA2S6 C. Aes D. RNGCryptoServiceProvider Answer: B --- ### 1.5. https://www.briefmenow.org/microsoft/which-type-of-block-should-you-use-5/ You are developing an application that will transmit large amounts of data between a client computer and a server. You need to ensure the validity of the data by using a __cryptographic hashing algorithm__. Which algorithm should you use? A. DES B. HMACSHA512 C. RNGCryptoServiceProvider D. ECDsa Answer: B --- ## 2. HashAlgorithm.ComputeHash ### 2.1. https://www.briefmenow.org/microsoft/which-code-segment-should-you-insert-at-line-05-68/ You are developing a method named ``GenerateHash`` that will create the hash value for a file. The method includes the following code. ``` public byte[] GenerateHash(string filename, string hashAlgorithm) { var signatureAlgo = HashAlgorithm.Create(); var fileBuffer = System.IO.File.ReadAllBytes(filename); } ``` You need to return the cryptographic hash of the bytes contained in the fileBuffer variable. Which code segment should you insert at line 05? A. ``` var outputBuffer = new byte[fileBuffer.Length]; signatureAlgo.TransformBlock(fileBuffer, 0, fileBuffer.Length, outputBuffer, 0); signatureAlgo.TransformFinalBlock(fileBuffer, fileBuffer.Length - 1, fileBuffer.Length); return outputBuffer; ``` B. ``` signatureAlgo.ComputeHash(fileBuffer); return signatureAlgo.GetHashCode(); ``` C. ``` var outputBuffer = new byte[fileBuffer.Length]; signatureAlgo.TransformBlock(fileBuffer, 0, fileBuffer.Length, outputBuffer, 0); return outputBuffer; ``` D. ``` signatureAlgo.ComputeHash(fileBuffer); ``` Answer: D --- ### [HashAlgorithm.ComputeHash Method](https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.hashalgorithm.computehash?view=netcore-3.1) * Namespace: ``System.Security.Cryptography`` * Computes the hash value for the input data. ``` public byte[] ComputeHash (byte[] buffer); ``` ``` public class Program { public static void Main() { string source = "Hello World!"; using (SHA256 sha256Hash = SHA256.Create()) { string hash = GetHash(sha256Hash, source); Console.WriteLine($"The SHA256 hash of {source} is: {hash}."); Console.WriteLine("Verifying the hash..."); if (VerifyHash(sha256Hash, source, hash)) { Console.WriteLine("The hashes are the same."); } else { Console.WriteLine("The hashes are not same."); } } } private static string GetHash(HashAlgorithm hashAlgorithm, string input) { // Convert the input string to a byte array and compute the hash. byte[] data = hashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(input)); // Create a new Stringbuilder to collect the bytes // and create a string. var sBuilder = new StringBuilder(); // Loop through each byte of the hashed data // and format each one as a hexadecimal string. for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } // Return the hexadecimal string. return sBuilder.ToString(); } // Verify a hash against a string. private static bool VerifyHash(HashAlgorithm hashAlgorithm, string input, string hash) { // Hash the input. var hashOfInput = GetHash(hashAlgorithm, input); // Create a StringComparer an compare the hashes. StringComparer comparer = StringComparer.OrdinalIgnoreCase; return comparer.Compare(hashOfInput, hash) == 0; } } // The example displays the following output: // The SHA256 hash of Hello World! is: 7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069. // Verifying the hash... // The hashes are the same. ``` --- ## Cryptography ### 1. https://www.briefmenow.org/microsoft/which-class-should-you-use-44/ You have an application that will send confidential information to a Web server. You need to ensure that the data is encrypted when it is sent across the network. Which class should you use? A. ``CryptoStream`` B. ``AuthenticatedStream`` C. ``PipeStream`` D. ``NegotiateStream`` Answer: A --- ### [CryptoStream Class](https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.cryptostream?view=netcore-3.1) * Namespace: ``System.Security.Cryptography`` * Defines a stream that links data streams to cryptographic transformations. ``` public class CryptoStream : System.IO.Stream ``` ### [AuthenticatedStream Class](https://docs.microsoft.com/en-us/dotnet/api/system.net.security.authenticatedstream?view=netcore-3.1) * Namespace: ``System.Net.Security`` * Provides methods for passing credentials across a stream and requesting or performing authentication for client-server applications. ``` public abstract class AuthenticatedStream : System.IO.Stream ``` ### [PipeStream Class](https://docs.microsoft.com/en-us/dotnet/api/system.io.pipes.pipestream?view=netcore-3.1) * Namespace: ``System.IO.Pipes`` * Exposes a Stream object around a pipe, which supports both anonymous and named pipes. ``` public abstract class PipeStream : System.IO.Stream ``` ### [NegotiateStream Class](https://docs.microsoft.com/en-us/dotnet/api/system.net.security.negotiatestream?view=netcore-3.1) * Namespace: ``System.Net.Security`` * Provides a stream that uses the Negotiate security protocol to authenticate the client, and optionally the server, in client-server communication. ``` public class NegotiateStream : System.Net.Security.AuthenticatedStream ``` --- # Regular expression ``Regex`` ## 1. https://www.briefmenow.org/microsoft/you-need-to-ensure-that-the-expression-syntax-is-evalua/ You are developing a C# application that has a requirement __to validate some string input data by using the ``Regex`` class__. The application includes a method named ``ContainsHyperlink``. The ``ContainsHyperlink()`` method will verify the presence of a URI and surrounding markup. The following code segment defines the ``ContainsHyperlink()`` method. ``` bool ContainsHyperlink(string inputData) { string regExPattern = "href\\s*=\\s*(?:"; return evaluator.IsMatch(inputData); } ``` A. ``var evaluator = new Regex(regExPattern, RegexOptions.CultureInvariant)`` B. ``var evaluator = new Regex(inputData)`` C. ``` var assemblyName = "Validation"; ... var evaluator = new Regex(regExPattern, RegexOptions.CultureInvariant) ``` D. ``var evaluator = new Regex(regExPattern, RegexOptions.Compiled)`` --- Answer: D B 明顯錯誤; A,C 感覺是相同的結果 ### [Regex Constructors] Namespace: ``System.Text.RegularExpressions`` Initializes a new instance of the Regex class. * ``Regex()`` Initializes a new instance of the Regex class. * ``Regex(String)``: Initializes a new instance of the Regex class for the specified regular expression. * ``Regex(SerializationInfo, StreamingContext)``: Initializes a new instance of the Regex class by using serialized data. * ``Regex(String, RegexOptions)``: Initializes a new instance of the Regex class for the specified regular expression, with options that modify the pattern. * ``Regex(String, RegexOptions, TimeSpan)``: Initializes a new instance of the Regex class for the specified regular expression, with options that modify the pattern and a value that specifies how long a pattern matching method should attempt a match before it times out. ### [RegexOptions Enum](https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regexoptions?redirectedfrom=MSDN&view=netcore-3.1) * ``CultureInvariant``: Specifies that cultural differences in language is ignored. For more information, see the "Comparison Using the Invariant Culture" section in the Regular Expression Options article. * ``Compiled`` Specifies that the regular expression is compiled to an assembly. This yields faster execution but increases startup time. This value should not be assigned to the Options property when calling the CompileToAssembly method. ### [How does RegexOptions.Compiled work?](http://stackoverflow.com/questions/513412/how-does-regexoptions-compiled-work) ### [Regex Class](https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex?view=netcore-3.1) Namespace: ``System.Text.RegularExpressions`` Represents an immutable regular expression. ``` public class Regex : System.Runtime.Serialization.ISerializable ``` The following example uses a regular expression to check for repeated occurrences of words in a string. The regular expression \b(?<word>\w+)\s+(\k<word>)\b can be interpreted as shown in the following table. Pattern | Description --- | --- \b | Start the match at a word boundary. (?<word>\w+) | Match one or more word characters up to a word boundary. Name this captured group word. \s+ | Match one or more white-space characters. (\k<word>) | Match the captured group that is named word. \b | Match a word boundary. ``` // Define a regular expression for repeated words. Regex rx = new Regex(@"\b(?<word>\w+)\s+(\k<word>)\b", RegexOptions.Compiled | RegexOptions.IgnoreCase); // Define a test string. string text = "The the quick brown fox fox jumps over the lazy dog dog."; // Find matches. MatchCollection matches = rx.Matches(text); // Report the number of matches found. Console.WriteLine("{0} matches found in:\n {1}", matches.Count, text); // Report on each match. foreach (Match match in matches) { GroupCollection groups = match.Groups; Console.WriteLine("'{0}' repeated at positions {1} and {2}", groups["word"].Value, groups[0].Index, groups[1].Index); } // The example produces the following output to the console: // 3 matches found in: // The the quick brown fox fox jumps over the lazy dog dog. // 'The' repeated at positions 0 and 4 // 'fox' repeated at positions 20 and 25 // 'dog' repeated at positions 50 and 54 ``` --- ## 2. https://www.briefmenow.org/microsoft/which-code-should-you-insert-at-line-03-22/ You are creating a console application named ``App1``. ```App1`` will validate user input for order entries. You are developing the following code segment: ``` Console.Write("Enter unit price: "); string price = Console.ReadLine(); [] Console.Write("Valid price"); else { Console.Write("InValid price"); } ``` You need to complete the code segment. The solution must ensure that prices are positive and have two decimal places. Which code should you insert at line 03? A. ``if (!Regex.IsMatch(price, @"^(-)?\d+(\.\d\d)?$"))`` B. ``if (Regex.IsMatch(price, @"^(-)?\d+(\.\d\d)?$"))`` C. ``` Regex reg = new Regex(@"^\d+(\.\d\d)?$")); if(reg.IsMatch(price)) { ``` D. ``` Regex reg = new Regex(@"^(-)?\d+(\.\d\d)?$")); if(reg.IsMatch(price)) { ``` Answer: C --- # IValidateableObject ## 1. https://www.briefmenow.org/microsoft/which-code-segment-should-you-use-1244/ You are developing a C# application that includes a class named ``Product``. The following code segment defines the ``Product`` class: ``` public class Product { public int Id { get; set; } public int CategoryId { get; set; } public string Name { get; set; } public bool IsValid { get; set; } } ``` You implement ``System.ComponentModel.DataAnnotations.IValidateableObject`` interface to provide a way to validate the ``Product`` object. The ``Product`` object has the following requirements: The ``Id`` property must have a value greater than zero. The ``Name`` property must have a value other than empty or null. You need to validate the ``Product`` object. Which code segment should you use? A. ``` public bool Validate() { IsValid = Id > 0 || !string.IsNullOrEmpty(Name); return IsValid; } ``` B. ``` public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { if (Id < 0) { yield return new ValidationResult("Product Id is required.", new[] { "Id" }); } if (string.IsNullOrEmpty(Name)) { yield return new ValidationResult("Product Name is required.", new[] { "Name" }); } } ``` C. ``` public bool Equals(Product productToValidate) { productToValidate.IsValid = productToValidate.Id > 0 || !string.IsNullOrEmpty(productToValidate.Name); return productToValidate.IsValid; } ``` D. ``` public ValidationResult Validate() { ValidationResult validationResult = null; if (Id < 0) { validationResult = new ValidationResult("Product Id is required."); } if (string.IsNullOrEmpty(Name)) { validationResult = new ValidationResult("Product Name is required."); } return validationResult; } ``` Answer: B --- ### [String.IsNullOrEmpty(String)](https://docs.microsoft.com/zh-tw/dotnet/api/system.string.isnullorempty?view=netcore-3.1) ``` public static bool IsNullOrEmpty (string value); ``` ### [IValidatableObject Interface](https://docs.microsoft.com/zh-tw/dotnet/api/system.componentmodel.dataannotations.ivalidatableobject?view=netcore-3.1) Provides a way for an object to be validated. ### [IValidatableObject.Validate(ValidationContext) Method](https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.ivalidatableobject.validate?view=netcore-3.1) Determines whether the specified object is valid. ``` public System.Collections.Generic.IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate (System.ComponentModel.DataAnnotations.ValidationContext validationContext); ``` ### [How do I use IValidatableObject?](https://stackoverflow.com/questions/3400542/how-do-i-use-ivalidatableobject) First off, thanks to @paper1337 for pointing me to the right resources... I'm not registered so I can't vote him up, please do so if anybody else reads this. Here's how to accomplish what I was trying to do. ``Validatable`` class: ``` public class ValidateMe : IValidatableObject { [Required] public bool Enable { get; set; } [Range(1, 5)] public int Prop1 { get; set; } [Range(1, 5)] public int Prop2 { get; set; } // implement IValidatableObject public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { var results = new List<ValidationResult>(); if (this.Enable) { Validator.TryValidateProperty(this.Prop1, new ValidationContext(this, null, null) { MemberName = "Prop1" }, results); Validator.TryValidateProperty(this.Prop2, new ValidationContext(this, null, null) { MemberName = "Prop2" }, results); // some other random test if (this.Prop1 > this.Prop2) { results.Add(new ValidationResult("Prop1 must be larger than Prop2")); } } return results; } } ``` Using ``Validator.TryValidateProperty()`` will add to the results collection if there are failed validations. If there is not a failed validation then nothing will be add to the result collection which is an indication of success. 若有錯,會加入 ``collection`` collection 若為空,就是代表成功 Doing the validation: ``` public void DoValidation() { var toValidate = new ValidateMe() { Enable = true, Prop1 = 1, Prop2 = 2 }; bool validateAllProperties = false; var results = new List<ValidationResult>(); bool isValid = Validator.TryValidateObject( toValidate, new ValidationContext(toValidate, null, null), results, validateAllProperties); } ``` __It is important to set ``validateAllProperties`` to ``false``__ for this method to work. When ``validateAllProperties`` is ``false`` __only properties with a ``[Required]`` attribute are checked__. This allows the ``IValidatableObject.Validate()`` method handle the conditional validations. --- # X509Certificate2 ## 1. https://www.briefmenow.org/microsoft/which-code-segment-should-you-insert-at-line-06-44/ An application uses X509 certificates for data encryption and decryption. The application stores certificates in the Personal certificates collection of the Current User store. On each computer, each certificate subject isunique. The application includes a method named ``LoadCertificate``. The LoadCertificate() method includes the following code. ``` X509Certificate2 LoadCertificate(string searchValue) { var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); var certs = store..Find( searchValue, false); ... } ``` The ``LoadCertificate()`` method must load only certificates for which the subject exactly matches the ``searchValue`` parameter value. You need to ensure that the LoadCertificate() method loads the correct certificates. Which code segment should you insert at line 06? A ``FindBySubjectName`` B. ``FindBySubjectKeyIdentifier`` C. ``FindByIssuerName`` D. ``FindBySubjectDistinguishedName`` Answer: D --- ### [X509FindType Enum](https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.x509findtype?view=netcore-3.1) * ``FindBySubjectName`` 1 The findValue parameter for the Find(X509FindType, Object, Boolean) method must be a string representing the subject name of the certificate. This is a __less specific search__ than that provided by the FindBySubjectDistinguishedName enumeration value. Using the FindBySubjectName value, the Find(X509FindType, Object, Boolean) method __performs a case-insensitive string comparison using the supplied value__. For example, if you pass "MyCert" to the Find(X509FindType, Object, Boolean) method, it will find all certificates with the subject name containing that string, regardless of other subject values. Searching by distinguished name is a more precise search. * ``FindBySubjectDistinguishedName`` 2 The findValue parameter for the Find(X509FindType, Object, Boolean) method must be a string representing the subject distinguished name of the certificate. This is a __more specific search__ than that provided by the FindBySubjectName enumeration value. Using the FindBySubjectDistinguishedName value, the Find(X509FindType, Object, Boolean) method __performs a case-insensitive string comparison for the entire distinguished name__. Searching by subject name is a less precise search. * ``FindByIssuerName`` 3 The findValue parameter for the Find(X509FindType, Object, Boolean) method must be a string representing the issuer name of the certificate. This is a __less specific search__ than that provided by the FindByIssuerDistinguishedName enumeration value. Using the FindByIssuerName value, the Find(X509FindType, Object, Boolean) method performs a case-insensitive string comparison using the supplied value. For example, if you pass "MyCA" to the Find(X509FindType, Object, Boolean) method, it will find all certificates with the issuer name containing that string, regardless of other issuer values. * ``FindBySubjectKeyIdentifier`` 14 The findValue parameter for the Find(X509FindType, Object, Boolean) method must be a __string representing the subject key identifier in hexadecimal__, such as "F3E815D45E83B8477B9284113C64EF208E897112", as displayed in the UI. --- ### [X509Certificate2 Class](https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.x509certificate2?view=netcore-3.1) * Namespace: ``System.Security.Cryptography.X509Certificates`` ``` private static X509Certificate2 GetCertificateFromStore(string certName) { // Get the certificate store for the current user. X509Store store = new X509Store(StoreLocation.CurrentUser); try { store.Open(OpenFlags.ReadOnly); // Place all certificates in an X509Certificate2Collection object. X509Certificate2Collection certCollection = store.Certificates; // If using a certificate with a trusted root you do not need to FindByTimeValid, instead: // currentCerts.Find(X509FindType.FindBySubjectDistinguishedName, certName, true); X509Certificate2Collection currentCerts = certCollection.Find(X509FindType.FindByTimeValid, DateTime.Now, false); X509Certificate2Collection signingCert = currentCerts.Find(X509FindType.FindBySubjectDistinguishedName, certName, false); if (signingCert.Count == 0) return null; // Return the first certificate in the collection, has the right name and is current. return signingCert[0]; } finally { store.Close(); } } ``` --- ### [X509Store Class](https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.x509store?view=netcore-3.1) * Namespace: ``System.Security.Cryptography.X509Certificates`` * Represents an X.509 store, which is a physical store where certificates are persisted and managed. This class cannot be inherited. ``` public class Example { static void Main() { Console.WriteLine("\r\nExists Certs Name and Location"); Console.WriteLine("------ ----- -------------------------"); foreach (StoreLocation storeLocation in (StoreLocation[]) Enum.GetValues(typeof(StoreLocation))) { foreach (StoreName storeName in (StoreName[])Enum.GetValues(typeof(StoreName))) { X509Store store = new X509Store(storeName, storeLocation); try { store.Open(OpenFlags.OpenExistingOnly); Console.WriteLine("Yes {0,4} {1}, {2}", store.Certificates.Count, store.Name, store.Location); } catch (CryptographicException) { Console.WriteLine("No {0}, {1}", store.Name, store.Location); } } Console.WriteLine(); } } } /* This example produces output similar to the following: Exists Certs Name and Location ------ ----- ------------------------- Yes 1 AddressBook, CurrentUser Yes 25 AuthRoot, CurrentUser Yes 136 CA, CurrentUser Yes 55 Disallowed, CurrentUser Yes 20 My, CurrentUser Yes 36 Root, CurrentUser Yes 0 TrustedPeople, CurrentUser Yes 1 TrustedPublisher, CurrentUser No AddressBook, LocalMachine Yes 25 AuthRoot, LocalMachine Yes 131 CA, LocalMachine Yes 55 Disallowed, LocalMachine Yes 3 My, LocalMachine Yes 36 Root, LocalMachine Yes 0 TrustedPeople, LocalMachine Yes 1 TrustedPublisher, LocalMachine */ ``` --- ### [OpenFlags Enum](https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.openflags?view=netcore-3.1) #### Fields ``IncludeArchived`` 8 Open the X.509 certificate store and include archived certificates. ``MaxAllowed`` 2 Open the X.509 certificate store for the highest access allowed. ``OpenExistingOnly`` 4 Opens only existing stores; if no store exists, the Open(OpenFlags) method will not create a new store. ``ReadOnly`` 0 Open the X.509 certificate store for reading only. ``ReadWrite`` 1 Open the X.509 certificate store for both reading and writing. --- # Unclassified ## https://www.briefmenow.org/microsoft/which-code-segment-should-you-insert-at-line-08-25/ You are developing an application that uses the Microsoft ADO.NET Entity Framework to retrieve ``order`` information from a Microsoft SQL Server database. The application includes the following code. ``` public DateTime? OrderDate; IQueryable<Order> LookupOrdersForYear(int year) { using (var context = new NorthwindEntities()) { var orders = from order in context.Orders select order; return orders.ToList().AsQueryable(); } } ``` The application must meet the following requirements: Return only ``orders`` that have an ``OrderDate`` value other than ``null``. Return only ``orders`` that were placed in the year specified in the year parameter. You need to ensure that the application meets the requirements. Which code segment should you insert at line 08? A. where order.OrderDate.Value.Year == year B. where order.OrderDate.HasValue && order.OrderDate.Value.Year == year C. where order.OrderDate.Value != null && order.OrderDate.Value.Year >= year D. where order.OrderDate.Value == null && order.OrderDate.Value.Year == year Answer: B ---