MCSD Certification Toolkit (Exam 70-483): Programming in C# by @SHANEBREWER

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

How do you define a symbol using compiler preprocessor directives? How do you undefine?

#define MySymbol #undef MySymbol #if MySymbol // Code here #endif

What are the #warning and #error preprocessor directives?

#warning and #error and used to report and error or warning to the compiler.

What is the function of Code Access Security (CAS)?

-Define permissions for accessing system resources -Enables code to demand that its callers have specific permission -Enables code to demand that its callers possess a digital signature -Enforces all those restrictions at runtime</

What are the benefits of strongly naming assemblies?

-Guarantees uniqueness -Protects your versioning as you have the private key so only you can update it -Provides a strong integrity check to determine if the assembly has changed since it was signed.

How do you create a Task?

1. Create an instance. Task t1 = new Task(Action a); t1.Start(); 2. Call the static TaskFactory.StartNew method Task t2 = TaskFactory.StartNew(Action a); 3. Call a static Task.Run method Task t3 = Task.Run(Action a); 4. Call one of the continuation methods -Task.WhenAll -Task.WhenAny -TaskFactory.ContinueWhenAll -TaskFactory.ContinueWhenAny

How do you put an assembly in the GAC?

1. Use a specific installation program such as Windows Installer 2.0 2. Use the "Gacutil.exe" utility Example gacutil -i [assembly name] // Install gacutil -u [assembly name] // Uninstall

How can you specify CAS in code?

2 methods Declarative CAS -Uses attributes to apply security information to your code Example [FileIOPermission(SecurityAction.Demand, AllLocalFiles = FileIOPermissionAccess.Read)] Imperative CAS -Ask permission in the code Example FileIOPermission f = new FileIOPermission(PermissionState.None); f.AllLocalFiles = FileIOPermissionAccess.Read; try { f.Demand(); } catch (SecurityException s) { Console.WriteLine(s.Message); }

How do you create a directory?

2 ways var directory = Directory.CreateDirectory(dir); var directoryInfo = new DirectoryInfo(dir); directoryInfo.Create();

What is the difference between CPU and I/O bound operations?

A CPU bound operation requires a thread to execute. In a client-application, it can make sense to execute a CPU-bound operation on another thread to improve responsiveness. In a server application, you don't want an extra thread for a CPU-bound opreation. An I/O bound operation don't require a thread while executing. Using asynchronous I/O frees the current thread to do other work and improves scalability.

What is a Child Task and how do you implement it?

A Child Task is a task that is created by another task (the parent). Task<int> parent = Task.Run(() => { var task = new Task<int>(() => return 1;, TaskCreationOptions.AttachedToParent).Start(); return task.Result; }); </int>

What is a Continuation Task and how do you implement it?

A Continuation Task is a Task that is run immediately after a Task has finished. Task<int> t = Task.Run(() => { return 42; } ).ContinueWith((i) => { return i.Result * 2; } );

What is a Delegate?

A Delegate is a type that references a method. They allow methods to be passed as parameters. Can be used to define callback methods. They are like a C++ Function pointer, but with Type Safety.

What is a Finalizer and how do you define it?

A Finalizer is a method that is called by the garbage collector, just prior to being collected, so that an object can clean up unmanaged resources (Such as file handles, database connections, etc) A Finalizer is nondeterministic. You can't be sure when they will be called. Example ~SomeType() { // Code to clean up resources }

What is a Program Database file (PDB)?

A PDB file annotates your applicatoin's code with additonal information useful during debugging. You can construct the compiler to create a PDB file by specifying the /debug:full or /debug:pdbonly switches A .NET PDB file contains: -Source file and and their lines -Local variable names

What is a Task?

A Task is an object that represents some work that should be done, tells you if the work is completed, and a result if the operation returns a result.

What is a Task Factory?

A TaskFactory is created with certain options and can then create multiple Task objects with those options. TaskFactory tf = new TaskFactory( TaskCreationOptions.AttachedToParent, TaskContinuationOptions.ExecuteSychronuously); tf.StartNew(() => ...

How do you define a Transaction?

A Transaction is a way of grouping mutliple queries together so data won't get corrupted. Example using(TransactionScope scope = new TransactionScope()) { // SQL Commands scope.Complete(); }

What is a Weak Reference? How do you implement a WeakReference?

A WeakReference is an object stored on the heap that doesn't have a reference to it. A WeakReference object will be garbage collected if garbage collection is run. Can be useful for caching large objects. Example static WeakReference data; public static void Run() { object result = GetData(); result = GetData(); } private static object GetData() { if(data == null) { data = new WeakReference(LoadLargeList()); } if(data.Target == null) { data.Target = LoadLargeList(); } return data.Target; }

What is the difference between a struct and a class in C#?

A class is a reference type. A struct is a value type. A class can be used in an inheritance hierarchy. A struct cannot. A class can declare static types. A struct cannot. A struct has a smaller memory footprint than a class.

What can implement an interface in c#

A class or a struct.

What is the difference between a Process and a Thread?

A process is an executing program. One or more threads run in the context of the process. A process runs in a separate memory space. A process has a virtual address space, executable code, open handles to system objects, a security context, a unique process identifier, environment variables, etc. A thread is the basic unit to which the operating system allocates processor time. Threads run in a shared memory space.

What is a reference type?

A reference type contains a reference to the real value which is stored on the heap. The address to the value is stored on the stack.

What is a strong-named assembly?

A strong-named assembly is signed with a public/private key pair that uniquely identifies the publisher of the assembly and the content of the assembly. A strong name consists of: -The text name of the assembly -The version number -Culture Information

What is symmetric and asymmetric encryption?

A symmetric algorithm uses one single key to encrypt and decrypt the data. You need to pass your original key to the receiver so he can decrypt your data. This leads to the problemm of securely exchanging keys. An asymmetric algorithm uses 2 keys that are mathematically related to each other. One key is public and can be ready by everyone and the other key is private and should never be shared with someone else. When you encrypt something with teh public key, it can be decrypted by using the private key and vice versa.

What is a ThreadPool?

A thread pool is a pool of threads so that once a thread is finished, it can be returned to the pool where it can be reused. This reuse avoids the cost of creating a new thread for each task. When you work with a thread pool, you queue a work item that is then picked up by an available thread from the pool. A thread pool limits the available number of threads, so there is a lesser degree of parallelism than the regular Thread class. A thread pool ensures that each request gets added to the queue and that when a thread becomes available, it is processed. A thread pool also ensures that you server doesn't crash under the amount of requests.

What is a trigger?

A trigger is a special method that is executed with your database is updated, inserted or removed.

What Text Encoding types are available?

ASCII BigEndianUnicode Unicode UTF32 UTF7

You have declared an event on your class and you want outside users of your class to raise this event. What do you do?

Add a public method to your class that raises the event.

What AttributeTargets Flags are available?

All Assembly Class Constructor Delegate Enum Event Field GenericParameter Interface Method Module Parameter Property ReturnValue Struct

What is an anonymous type and how do you define one?

An Anonymous type uses object initializers and implicit type to create a type that is shaped at compile time without having a formal class definition. Example var person = new { FirstName = "John", LastName = "Doe" };

What is an Event?

An Event is used to provide notifications. You can subscribe to an event if you are interested in those notifications.

What are expression trees?

An expression tree is a representation of code in a tree like structure. An expression tree describes code instead of being the code iteself. Expression trees are heavily used in LINQ.

What is an indexer?

An indexer enables instances of your class or struct to be accessed just like an array. Example class Card { } class Deck { public IColelction<Card> Cards { get; private set; } public Card this[int index] { get { return Cards.ElementAt(index); } } }

How do you perform an outer join using LINQ?

An outer join selects all elements from one sequence even if there is not a matching element in the second sequence. from e in employees join s in states on e.StateID equals s.StateID into newGroup from item in newGroup.DefaultIfEmpty( new State { StateID = 0, StateName = "" }) select new {e.LastName, item.Statename };

What collections can LINQ query?

Any collection of objects that implements IEnumerable/IEnumerable<T> or IQueryable/IQueryable<T> interfaces.

What can attributes be added to?

Assemblies Types Methods Parameters Properties

How do you create an instance using Reflection?

Assembly assembly = Assembly.Load("System.Data"); DataTable dt = (DataTable)assembly.CreateInstance("System.Data.DataTable);

What Concurrect Collections are provided by the .Net framework?

BlockingCollection<T>: Thread safe collection. Removing blocks until data becomes available. Adding is fast and blocks when reaching a set limit until there is room. ConcurrentBag<T>: An unordered bag of items. ConcurrentDictionary<T>: Stores key and value pairs in a thread-safe manner. ConcurrentQueue<T>: A LILO collection ConcurrentStack<T>: A LIFO collection

What is Boxing and Unboxing?

Boxing the process of taking a value type, putting it inside a new object on the heap, and storing a reference to it on the stack. Unboxing takes the item from the heap and returns a value type that contains the value from the heap.

What options for profiling your application are available in Visual Studio?

CPU Sampling: Lightweight Instrumentation: Injects code to captures timing information for each function that is called. .NET memory allocation: Gives an idea of how memory is being used in your program. Resource contention data: Used in multithreaded applications to find out why methods have to wait for each other.

What is the difference between implementing an interface and inheriting a class?

Class inheritance represents a "is-a" relationship. Eg: A child is a human. A class can only inherit from a single class. Implementing an interface is defining a "can-do" relationship. Eg: A class can do disposing. A class or a struct can implement multiple interfaces.

How do you change where Trace information is written?

Clear the current listeners collection and add a new TraceListener(s) to the list. Example: Stream output = File.Create("tracefile.txt"); TextWriterTraceListener textListener = new TextWriterTraceListener(output); TraceSource traceSource = new TraceSource("myTraceSource", SourceLevels.All); traceSource.Listeners.Clear(); traceSource.Listeners.Add(textListener);

What are the main classes in CodeDom?

CodeCompileUnit: The top-level class that is a container for all other objects. CodeNamespace and CodeNamespaceImport: Used to represent the namespace and import statements. CodeTypeDeclaration: Declares a type in the file (Class) CodeMemberField: Adds a fields to the class. CodeMemberProperty: Adds a property to the class. CodeMemberMethod: Adds a method to the class. CodeParameterDeclarationExpression: Declares a parameter to a method. CodeMethodInvokeExpression: Create a call to a method. CodeDomProvider: Generates the code

How can you generate dynamic code in C#?

CodeDOM Expression Trees

How do you generate code using CodeDOM?

CodeDOM looks at your source file as a tree with containers. You have a topmost container (called a CodeCompileUnit) that contains other elements such as namespaces, classes, methods, and individual statements. Example CodeCompilerUnit compileUnit = new CodeCompileUnit(); CodeNamespace myNamespace = new CodeNamespace("MyNamespace"); myNamespace.Imports.Add(new CodeNamespaceImport("System")); CodeTypeDecelaration myClass = new CodeTypeDeclaration("MyClass"); CodeENtryPointMethod start = new CodeEntryPointMethod(); CodemethodInvokeExpression cs1 = new CodeMethodInvokeExpression( new CodeTypeReferenceExpression("Console"), "WriteLine", new CodePrimitiveExpression("Hello World")); compileUnit.Namespaces.Add(myNamespace); myNamespace.Types.Add(myClass); myClass.Members.Add(start); start.Statements.Add(cs1);

What is the Convert class used for?

Convert is used to convert between base types. A null argument will provide the default value of the type being converted to. Example: int i = Convert.ToInt32(null);

What is Covariance and Contravariance? How are they used with delegates?

Covariance makes it possible that a method has a return type that is more derived than that defined in the delegate. Contravariance makes it possible that a method has parameter types that are less derived than those in the delegate type. Example public delegate TextWriter CovarianceDel(); public StreamWriter MethodStream() { } CovarianceDel del; del = MethodStream(); // StreamWriter inherits from TextWriter void DoSomething(TextWriter tw) { } public delegate void ContravarianceDel(StreamWriter sw); ContravarianceDel del = DoSomething;

How do you create an XML Document in C#?

Create an XElement object to build an XML hierarchy and then use the Save method to write the XML document. Example XElement root = new XElement("Root", new List<XElement> { new XElement("Child1"), new XElement("Child2"), new XElement("Child3") }, new XAttribute("MyAttribute", 42)); root.Save("test.xml");

What levels are available for a TraceEventType?

Critical: For very serious and irrecoverable errors Error: Indicates that something is wrong Warning: Something unusual has occurred that may be worth investigating further. Information: Process is executing correctly, but there may be some interesting infoermation to include Verbose: For information that is not indicating anything is wrong. Stop, Start, Suspend, Resume, Transfer: Mark the trace event as relating to the logical flow of the application.

What is CultureInfo and how do you create an object?

CultureInfo contains information regarding how information is displayed in a given culture. Example: CultureInfo provider = new CultureInfo("en-US");

What are the format strings for Currency, Short Date, Long Date and Month/Date only?

Currency = C Short Date = d Long Date = D Month Date = M

How do you obtain the constructors from an instance using Reflection?

DataTable myDataTable = new DataTable(); Type myDataTableType = myDataTable.GetType(); ConstructorInfo[] = myDataTableConstructors = myDataTableType.GetConstructors(); ParameterInfo[] parameters = ConstructorInfo[0].GetParameters();

How do you define a custom attribute?

Define a new class that derives from the Attribute class. Example public class CategoryAttribute : Attribute { }

What are digital certificates?

Digital certifcates use hashing and asymmetric encryption to authenticate the identity of any object signed by the certificate. Also help with protecting the integrity of data as if the message is changed, the hash is also changed.

What is the difference between Dispose and Finalize?

Dispose is called by the application to dispose of unmanaged and managed resources. A Finalizer is called by the Garbage Collector to dispose of unmanaged resources.

What is an explicit interface implementation?

Explicit interface implementation means that an interface type element can be accessed only when using the interface directly. Is used to: -Hide members of a class to outside users -Required when a class implements 2 interfaces that contain duplicate method signatures. Example interface IInterfaceA { void MyMethod(); } class Implementation : IInterfaceA { void IInterfaceA.MyMethod() { } }

What are Extension Methods and how do you define one?

Extension Methods are methods that can be added to an existing type. Example public static class MyExtensions { public static decimal Discount(this Product p) { return p.Price * 0.9; } }

How do you retrieve data from a WCF Web Service?

ExternalService.MyServiceClient client = new ExternalService.MyServiceClient(); string result = client.DoWork("John", "Doe");

How do you create a strong named assembly?

Generate a key pair Visual Studio or "sn -k myKey.snk" command

What is Grouping in LINQ? How do you implement it?

Grouping is when you group your data by a certain property and then work with that result. Example var result = from o in orders from l in o.OrderLines group l by l.Product into p select new { Product = p.Key, Amount = p.Sum(x => x.Amount ) };

How do you implement asynchronous I/O operations?

HttpClient client = new HttpClient(); Task microsoft =client.GetStringAsync("http://www.microsoft.com"); Task msdn = client.GetStringAsync("http://www.msdn.com"); Task blogs = client.GetStringAsync("http://blogs.msdn.com"); await Task.WhenAll(microsoft, msdn, blogs);

What types of type conversion are available in C#?

Implicit conversions Explicit conversions User-defined conversions Conversion with a helper class

How do you define a user-defined implicit and explicit conversion?

Implicit conversions public static implicit operator decimal (Money m) { return m.Amount; } Explicit conversions public static explicit operator int (Money m) { return (int)m.Amount; }

How do you define the version of an assembly?

In the AssemblyInfo.cs file: The AssemblyFileVersionAttribute should be incremented with each build. The AssemblyVersionAttribute should be incremented manually with each deploy.

What is the String.IndexOf method?

IndexOf return the index of the first occurrence of a character or substring within a string. Example string value = "My Sample Value"; int indexOfp = value.IndexOf('p'); // returns 6

How do you create a custom attribute?

Inherit from System.Attribute. Example: public class CategoryAttribute : Attribute { public CategoryAttribute(string value) : base("Category", value) { } }

What is a Lambda Expression?

Is is a compact method to create an anonymous method. The => can be read as "becomes" or "for which". Eg. x,y becomes x + y

How does the .Net framework handle exceptions in a parallel query?

It aggregates all exceptions in one AggregateException object. This exception exposes a list of all exceptions that have happened during a parallel execution. try { // Parallel query } catch (AggregateException e) { Console.WriteLine(e.InnerExceptions.Count); }

How does a Task signal to outside users that it has been cancelled?

It can use a CancellationToken to throw a OperationCanceledException Example token.ThrowIfCancellationRequested();

What is the Conditional Attribute for?

It instructs the compiler to ignore a method call unless a specific compiler option is specified. Example [Conditional("CONDITION1"), Conditional("CONDITION2")]

What is a SqlDataReader?

It is a forward only stream of rows from issuing a query to the database. Example while(await dataReader.ReadAsync()) { Console.WriteLine(dataReader["id"]); }

What is an auto-implemented property?

It is a shorthand notation for a property. Example public int Value { get; set; }

What is a Task Scheduler?

It is responsible for starting a Task and managing it. The Task Scheduler uses threads from the thread pool to execute the Task.

What is the ?? operator?

It is the Null-Coalescing operator that is used to provide a default value for nullable value types or reference types. Example int? x = null int y = x ?? -1;

What is the GetConsumingEnumerable method for?

It returns an IEnumerable that blocks until it finds a new item. That way you can use a foreach statement with your BlockingCollection. Example foreach(string v in collection.GetConsumingEnumerable()) Console.WriteLine(v);

What is the conditional attribute?

It signals to the compiler that a method call should be ignored unless a specific compiler option is specified. Example [Conditional("Condition1"), Conditional("Condition2")] static void MyMethod() { }

How does CAS determine if a method has the required permissions?

It walks the call stack to make sure that EVERY method on the call stack has the appropriate permissions. This way a less-trusted method cannot call some restricted code through a highly trusted method.

What is the "Join" operator in LINQ? How do you utilize it?

Join is used to combine data from two or more sources. When using it you have to specify the property that needs to be equal. Example string[] names = { "A", "B" }; var popularProducts = from p in products join n in names on p.Description equals n select p;

How do you avoid deadlocks in your code?

Make sure that locks are requested in the same order. Don't lock on the "this" object. Don't lock on a string.

How do you make a class Serializable with XmlSerializer? How do you Serialize an object?

Make your types with the [Serializable] attribute. Create a XmlSerializer object for the type. Create a stream. Pass the stream and the object to the XmlSerializer object. XmlSerializer serializer = new XmlSerializer(typeof(Person)); string xml; using(StringWriter stringWriter = new StringWriter()) { serializer.Serialize(stringWriter, p); xml = stringWriter.ToString(); }

You are using a multicast delegate with multiple subscribers. You want to make sure that all subscribers are notified, even if an exception is thrown. What do you do?

Manually raise the events by using GetInvocationList to get a list of event handlers and then invoke them using the Invoke method. Example foreach(EventHandler d in someEvent.GetInvocationList()) d.Invoke(null, null);

What can a struct contain? What can a struct not contain?

Methods Fields Properties Constructors Constants Indexers Operators Events Nested Types Implement Interface A struct cannot Inherit Define static members

What is the equivalent code that is generated by the "lock" keyword?

Monitor.Enter and Monitor.Exit

What is Multicasting?

Multicasting is combining delegates together using the + or += operator to add another method to the invocation list of an existing delegate instance. Example public delegate void ExampleDelegate(); ExampleDelegate d = MethodOne; d += MethodTwo; d(); // Executes both methods

What are Named Arguments?

Named Arguments help you specify which arguments you want to pass a value to. Example: void Method(int a, int b = 0, string c = "default") { } Method(a, c: "me");

What Performance Counter Types are available?

NumberOfItems32/NumberOfItems64: To count the number of operations or items RateOfCountsPerSecond32/RateOfCountsPerSecond64: To count the amount per second of an item or operation AvergateTimer32: Calculates the average time to perform a process or process an item.

What are optional arguments?

Option arguments enable you to omit arguments for some parameters. Example void Method(int a, int b = 0) { } Method(1); // Will have 0 as it's 2nd argument

What is the "OrderBy" clause used for in LINQ?

OrderBy is used to sort your data in ascending or descending order. Example var result = from d in data where d > 3 orderby d descending select d;

What is Paging in LINQ? What is the benefits of using it? How do you utilize it?

Paging loads data from a source 1 page at a time. When data comes from an external resource (such as a database), paging can help improve performance. You implement paging using the "Skip" and "Take" operators (Method syntax only). Example var pagedOrders = orders.Skip((pageIndex - 1) * pageSize) .Take(pageSize);

How do you Parallelize a For Loop?

Parallel.For(0, 10, i => { return i*2; });

How do you Parallelize ForEach?

Parallel.ForEach(collection, i => { return i * 2; });

How do you initialize an object and it's properties at the same time?

Person p = new Person { FirstName = "John", LastName = "Doe" };

What access modifiers are available in C#

Private Protected Public Internal (Internal to the assembly) Protected Internal (In a subclass OR in the assembly)

How should you store a private key?

Private keys should be stored in a "Key Container" which provided functionality for saving a loading the key. Example string key = "Secret"; CspParameters csp = new CspParameters() { KeyContainer = key }; byte[] encryptedData; using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(csp)) { encryptedData = RSA.Encrypt(dataToEncrypt, false); }

What is profiling?

Profiling is the process of determining how your application uses certain resources such as memory, which methods are being called, and how long each method takes to execute. It is used to identify bottlenecks.

What is Projection in LINQ? How do you implement it?

Projection is when you select another type or an anonymous type as the result of your query. Example: var result = from o in orders from l in o.OrderLines group l by l.Product into p select new { Product = p.Key, Amount = p.Sum(x => x.Amount ) };

What is the difference between readonly and const?

Readonly allows the field to be set only once during construction: At definition or in the constructor. Const allows the field to be set at the definition.

What is reflection?

Reflection enables an application to collection information about itself and act on this information. Reflection is computationally expensive.

How do you iterate through a DBDataReader object?

SQLDataReader dr = command.ExecuteReader(); if(dr.HasRows) { while(dr.Read()) { Console.WriteLine(dr["First Name"]); } }

How do you utilize a DataSet?

SqlDataAdaptor da = new SqlDataAdapter("SELECT * FROM Person", connection); DataSet ds = new DataSet(); da.Fill(ds, "Person"); foreach (DataRow row in ds.Tables[0].Rows) { Console.Writeline(row["FirstName"]); }

Is String a reference type or a value type?

String is a reference type that looks like a value type. == and != are overloaded to compare on value, not on reference. String is immutable so it cannot be changed after it has been created. Every change will result in a new string.

What is the StringBuilder class?

StringBuilder represents a mutable string so changes can be made to it. StringBuilder can offer better performance in certain situations over String. Example StringBuilder sb = new StringBuilder("Initial Value");

How do you wait for multiple Tasks to be finished?

Task.WaitAll(tasks);

How do you wait for 1 Task out of several to be finished?

Task.WaitAny(tasks);

What is the difference between the "LoadFrom" and "LoadFile" methods in the Assembly class?

The "LoadFrom" method first looks in the load context (Assemblies found by probing the GAC, the host assembly store, the folder of the executing assembly) to find the assembly. Thus you may get what you are expecting and you may not. The "LoadFile" method just attempts to load the assembly give in the parameter. The Load method is the recommended method to load an assembly.

What is the "Using" keyword?

The "Using" keyword is used by types that implement the IDisposable interface. The compiler wraps the type with a Try-Finally block to make sure that unmanaged resources are freed in the case of an exception.

What is the "dynamic" keyword in C#?

The "dynamic" keyword tells the compiler to stop static type checking. It saves the intent of the code so that it can be later executed at runtime. This is useful when communicating with external resources such as COM Interop, Iron-Python, JavaSceript Object Notation (JSON) result sets, or the HTML Document Object Model (DOM) or when working with reflection inside C#. Example dynamic d = new ExampleClass(); d.exampleMethod(10, 4);

What are the "is" and "as" keywords used for in C#?

The "is" operator returns true or false if the conversion is allowed. The "as" operator returns the converted value or null if the conversion is not possible. Examples DbConnection c; if(c is SqlConnection) { } Stream stream = new MemoryStream(); MemoryStream memStream = stream as MemoryStream; (if memStream != null) { }

How do you view the public key of a strong assembly?

The "sn -Tp" command Example sn-Tp C:\Windows\Microsoft.Net\Framework\v4.0.30319\System.Data.dll

What is the #line preprocessor directive used for?

The #line directive is used to modify the compiler's line number and even the name of the file. Example #line 200 #line default #line hidden

What is the ConditionalAttribute used for?

The ConditionalAttribute tells the compiler to include calls to a method only if the condition is true. Example [Conditional("DEBUG")] private void Log(string message) { }

What is the Debug class and how do you use it?

The Debug class is used for basic logging and assertions. Example Debug.WriteLine("Example"); Debug.Indent(); // Increases indent level Debug.Assert(i == 0); Debug.WriteLineIf(i > 0, "i is greater than 0");

What is the DebuggerDisplayAttribute?

The DebuggerDisplayAttribute is used by the debugger to display an object without having to override the ToString method. <DebuggerDisplay("Name = {FirstName} {LastName}")] public class Person { public string FirstName { get; set; } public string Lastname { get; set; } }

What is DynamicObject?

The DynamicObject is a base class that enables you to define which operations can be performed on dynamic objects and how to perform those operations. The class is useful if you want to create a more convenient protocol for a library.

What is ExpandoObject?

The ExpandoObject enables you to add and delete members of its instances at runtime and also to set and get values of these members.

What is the IComparable interface?

The IComparable interface is used to sort elements. A single method CompareTo retunrs an int value that shows how 2 elements are related. <0 - The Current instance precedes the argument 0 - The current instance is the same sort order as the argument >0 - The current instance follows the argument

What is the IDisposable interface?

The IDisposable interface is used to facilitate working with external, unmanged resources. The Dispose method is used to free any resources.

What is the IEnumerable interface?

The IEnumerable interface helps you to implement the iterator pattern which enables you to access all elements in a collection without caring about how it's exactly implemented. The IEnumberable interface exposes a GetEnumerator method that returns an enumerator. The Enumerator has a MoveNext method that returns the next item in the collection.

What is the IFormatProvider interface?

The IFormatProvider provides specific information for formatting a type for things like culture-specific layouts. All CultureInfo objects implement IFormatProvider.

What is the IUnknown interface?

The IUnknown interface can be used when you want to create a wrapper class to access DLL or COM functions.

What is the Interlocked class?

The Interlocked class is used to create atomic operations. Examples: int n = 0; Interlocked.Increment(ref n); Interlocked.Decrement(ref n);

What is the String.LastIndexOf method?

The LastIndexOf finds the index of the last occurence of a character or substring.

What does the Lock keyword do?

The Lock keyword puts a lock on an object to block other threads that are trying to access/update data. Example: private static object _lock; lock(_lock) { // Do stuff here }

What tool do you use to create a digital certificate?

The Makecert.exe tool Example Makecert output.cer

What are the Parse and TryParse methods used for?

The Parse and TryParse methods are used when you have a string that you want to conver to a specific data type. Parse should be used if you are certain the parsing will succeed. TryParse should be used if you are not sure that the parsing will succeed. Example string value = "true"; bool b = bool.Parse(value); string value = "1"; int result; bool success = int.TryParse(value, out result); if(success) { }

How does a SqlDataReader handle results from multiple batched SQL Statements?

The SqlDataReader contains mutiple result sets. You can advance to the next result set by calling NextResult or NextResultAsync on the SqlDataReader object.

What is the Substring method?

The Substring method can be used to retrieve a partial string from another string. Parameter are the start index and the length of the substring. Example string value = "My Sample Value"; string subString = value.SubString(3, 6); // returns 'Sample'

What is the TraceSource class? How do you use it?

The TraceSource class provides methods to enable applications to trace the execution of code. Example TraceSource traceSource = new TraceSource("myTraceSource", SourceLevels.All); traceSource.TraceInformation("Tracing application"); traceSource.TraceEvent(TraceEventType.Critical, 0, "Critical Trace"); traceSource.TraceData(TraceEventType.Information, id, new object[] { "a", "b", "c" }); traceSource.Flush(); traceSource.Close();

What is the "Where" clause used for in LINQ?

The Where clause acts as a filter and returns a boolean value if the value should be included in the final result. Example int[] data = { 1, 2, 3, 4, 5 }; var result = from d in data where d > 3 select d;

What is the XmlWriter class?

The XmlWriter class is used to create an Xml file. Example StringWriter stream = new StringWriter(); using(XmlWriter writer = XmlWriter.Create(stream, new XmlWriterSettings() { Indent = true })) { writer.WriteStartDocument(); writer.WriteStartElement("People"); writer.WriteStartElement("Person"); writer.WriteAttributeString("firstName", "John"); writer.WriteEndElement(); writer.Flush(); }

What functionality does the Event keyword provide?

The compiler protects your field from unwanted access. In particular, an event cannot be directly assigned to (=) but only provides subscription (+=). This prevents others from removing all previous subscriptions. No outside users can raise the event. It can only be raised by code that's part of the class that defined the event.

Which ways can you use to obtain a type object of an instance?

The typeof keyword. System.Type type = typeof(int); The GetType() method. System.Type type = myIntVariable.GetType();

What is a Concurrent Collection?

These collections are thread-safe which means that they internally use synchronization to make sure that they can be accessed by multiple threads at the same time.

How do you change a thread's priority?

Thread t = new Thread(new ThreadStart(ThreadMethod)); t.IsBackground = true;

How do you stop a thread?

Thread.Abort() method, but an exception is thrown on the target thread. This can potentially leave a corrupt state and make your application unusable. Can also use a shared variable.

How do you wait for a Thread to finish? A work item on the ThreadPool? A Task?

Thread: t.Join(); ThreadPool: WaitHandle.WaitAll(ManualResetEvent[]); Task: t.Wait();

What is the difference between Tracing and Logging?

Tracing can generate a huge amount of information and is enabled when you need to solve an issue in a production application. Logging is always enabled and is used for error reporting. You can use the Debug class for basic logging.

How do you hide a compiler warning?

Use #pragma warning disable #pragma warning restore

How do you return a ordered PLINQ query list?

Use AsOrdered() Example: var parallelResult = numbers.AsParallel().AsOrdered().Where(i => i % 2 == 0).ToArrary();

How do you execute a part of your PLINQ query sequentially?

Use AsSequential() Example: var parallelResult = numbers.AsParallel().AsOrdered().Where(i => i %2 == 0).AsSequential();

How do you communicate over the network in C#?

Use WebRequest and WebResponse classes. Example WebRequest request = WebRequest.Create("http://www.microsoft.com"); WebResponse response = request.GetResponse(); StreamReader rs = new StreamReader(response.GetResponseStream()); string r = r.ReadToEnd();

How do you create make sure thread arrive at a certain point before they continue?

Use a Barrier object. Create a barrier object with the number of threads to wait for and a delegate with the code to execute when all threads arrive. A thread notifies it has reached the barrier by calling SignalAndWait(). A thread notifies it is not continuing by calling RemoveParticipant.

How do you wait for several threads to finish?

Use a CountdownEvent object.

How do you deserialize a JSON string into an object?

Use a JavaScriptSerializer object. Example var serializer = new JavaScriptSerializer(); var result = serializer.Deserialize<Dictionary<string, object>>(json); If the JSON is invalid, an ArgumentException is thrown.

How do you pass a parameter to a thread start method?

Use a ParameterizedThreadStart delegate. public static void ThreadMethod(object o) { } Thread t = new Thread(new ParameterizedThreadStart(ThreadMethod)); t.Start(5);

How do you issue a command to a database?

Use a SQLCommand. Example SqlCommand command = new SqlCommand("SELECT * FROM People", connection); SqlDataReader dr = await command.ExecuteReaderAsync();

How do you connect to a Database?

Use a connection string. Example using(SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); // Execute operations against the database } The connection string might look like: "Persist Security Info=False; Integrated Security=true; Initial Catalog=Northwind;server=(local)"

You have a private method in your class and you want to make invocation of the method possible by certain callers. What do you do?

Use a method that returns a delegate to authorized callers.

How do you redirect one version of an assembly to another?

Use a publisher policy file with the upgraded assembly. <assemblyIdentity name="myAssembly" publicKeyToken="32ab4ba45e0a69a1" culture="en-us" /> <bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0" />

How do you jump from the execution of one case statement to another case statement in a switch statement?

Use goto to jump to case statement. Example goto case 2;

How do you guard against SQL injection attacks?

Use parameterized SQL statements. Example SqlCommand command = new SqlCommand("INSERT INTO People([FirstName], [LastName]) VALUES (@firstName, @lastName)", connection); await connection.OpenAsync(); Command.parameters.AddWithValue("@firstName", "John"); Command.parameters.AddWithValue("@lastName", "Dow"); int rows = await command.ExecuteNonQueryAsync();

How do you check to see if an attribute has been defined?

Use the "IsDefined" method in the Attribute class. Example if (Attribute.IsDefined(typeof(Person), typeof(SerializableAttribute))) { }

How do you specify a constraint on a Generic Type? Which constraints are available?

Use the "Where" clause. Examples where T : struct - The Type argument must be a value type where T : class - The Type argument must be a reference type where T : new() - The Type must have a public default constructor where T : <base class> - The Type must be or derive from the specified base class where T : <interface name> - The Type must implement the specified interface. Multiple interface constraints can be specified where T : U - The Type argument supplied for T must be or derive from the argument supplied for U.

How do you get the default value of a Generic type?

Use the "default(T)" keyword. Example public void MyMethod<T>() { T defaultValue = default(T); }

How do you allow multiple instances of an attribute to be applied to an element?

Use the AllowMultiple parameter to the AttributeUsage attribute. Example [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]

How do you execute a PLINQ query?

Use the AsParallel() to turn the query into a parallel one. The runtime determines if it makes sense to turn your query into a parallel one. Example: var numbers = Enumberable.Range(0, 100000); var parallelResult = numbers.AsParallel().Where(i => i%2 == 0).ToArrary();

How do you load an assembly using Reflection? How do you load a type using Reflection?

Use the Assembly.Load("Assembly Name") method. Example Assembly assembly = Assembly.Load("assemblyname"); Type[] types = assembly.GetTypes(); or Type[] types = assembly.GetExportedTypes(); // Gets public types

How does a C# program check if an attribute has been applied?

Use the Attribute class, from which all other attributes inherit. Example [Serializable] class Person { } if (Attribute.IsDefined(typeof(Person), typeof(SerializableAttribute))) { }

How do you define the targets of a custom attribute?

Use the AttributeUsage attribute with AttributeTargets parameters. Example [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] public class MyAttribute : Attribute { }

How do you unblock the UI on a Windows Forms/WPF application (Pre .Net 4.5)?

Use the BackgroundWorker class. 1. Create a method that follows the DoWorkEventHandler delegate. void DoWorkEventHandler(Object o, DoWorkEventArgs e) 2. In this method, call the long-running method. Assign the result to the Result property of the DoWorkEventArgs object. 3. Create a BackgroundWorker instance. 4. Use the method from step 1 and subscribe to the DoWork event. 5. Create a method that follows the RunWorkerCompletedEventHandler signarture. 6. In this method, get the result of the long-running operation and update the UI. 7. Subscribe that method to the RunWorkerCompleted event. 8. Call the RunWorkerAsync method.

How do you consume JSON documents?

Use the DataContractJsonSerializer class with [DataContract before the declaration of the class and [DataMember] attributes in front of fields or properties. Call the WriteObject method. Example: [DataContract] public class Person { [DataMember] private int id; } Stream stream = new FileStream("Person.json", FileMode.Create); DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person)); ser.WriteObject(stream, person); stream.Close();

How do you build a connection string dynamically?

Use the DbConnectionStringBuilder classes. Example var sqlConnectionStringBuilder new SqlConnectionStringBuilder(); sqlConnectionStringBuilder.DataSource = @"(localdb)\v11.0"; sqlConnectionStringBuilder.InitialCatalog = "ProgrammingInCSharp"; string connectionString = sqlConnectionStringBuilder.ToString();

How do you update the UI in a WPF application?

Use the Dispatcher Property. Example this.Dispatcher.Invoke(() => lblResult.Context = e.Result);

How do you access a Drive in C#?

Use the DriveInfo class. Example DriveInfo[] drivesInfo = DriveInfo.GetDrives(); driveInfo.IsReady driveInfo.Name driveInfo.DriveType driveInfo.AvailableFreeSpace

How do you write to the Windows Event Log?

Use the EventLog class in the System.Diagnostics namespace. You must have administrator privledges. Example if(!EventLog.SourceExists("MySource")) { EventLog.CreateEventSource("MySource", "MyNewLog"); return; // Restart application } EventLog myLog = new EventLog(); myLog.Source = "MySource"; myLog.WriteEntry(Log event!");

How do you wait for a thread(s) from the ThreadPool to be completed?

Use the EventWaitHandle Class. Create an EventWaitHandle object. When the thread is finished, call the Set method to signal that the work has been completed. Wait for the thread to be completed with the WaitOne() method. Example EventWaitHandle e = new EventWaitHandle(false, EventResetMode.ManualReset); ThreadPool.QueueUserWorkItem((x) => { result += ReadDataFromIO(); e.Set(); }); e.WaitOne();

How do you update data in a database?

Use the ExecuteNonQuery or ExecuteNonQuery-Async method to do this. Example SqlCommand command = new SqlCommand("UPDATE People SET FirstName='John'", connection); await connection.OpenAsync(); int numRowsUpdated = await command.ExecuteNonQueryAsync();

How do you generate code using an expression tree?

Use the Expression class Example BlockExpression blockExpr = Expression.Block( Expression.Call(null, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(String) }), Expression.Constant("Hello World!")));

How do you work with Files in C#?

Use the File class Examples: File.Exists(path) File.Delete(path); File.Move(path, destPath);

How can you use one enum to set multiple combinations of values?

Use the Flags attribute. Example [Flags] enum Days { Monday = 0x2, Tuesday = 0x4, Wendesday = 0x8 .... } Days example = Days.Monday | Days.Tuesday;

How do you iterate over all elements in parallel in a parallel collection?

Use the ForAll operator to iterate over a parallel enumberable collection. Example: var parallelResult = numbers.AsParallel().Where(i => i%2 == 0); parallelResult.ForAll(e => Console.WriteLine(e));

How do you manually call the garbage collector?

Use the GC.Collect(); This is NOT recommended in most situations.

How do you prevent the Garbage Collector from calling a Finalizer?

Use the GC.SuppressFinalize(this); method.

How do you wait for all Finalizers to be finished before continuing?

Use the GC.WaitForAllPendingFinalizers();

How do you retrieve a specific instance of an attribute? (To look at its properties for example)

Use the GetCustomAttribute method in the Attribute class. Example ConditionalAttribute conditionalAttribute = (ConditionalAttribute) Attribute.GetCustomAttribute( typeof(ConditoinalClass), typeof(ConditionalAttribute)); string condition = conditonalAttribute.ConditionString; // returns Condition1

How do you look at the properties of a specific instance of an attribute?

Use the GetCustomAttribute method. Example ConditionalAttribute att = (ConditionalAttribute)Attribute.GetCustomAttribute( typeof(ConditionalClass), typeof(ConditionalAttribute)); string condition = att.ConditionString;

How do you get an Assembly object of the current Assembly?

Use the GetExecutingAssembly static method. Example Assembly assembly = Assembly.GetExecutingAssembly();

How do you obtain the fields of a type using Reflection? How do you get the value of a field?

Use the GetField and GetFields methods of a Type object. You can also specify BindingFlags to indicate what kind of fields you wish to obtain. Example Type type = typeof(reflectionExample); FieldInfo field = type.GetField("MethodName"); FieldInfo[] field = type.GetFields(BindingFlags.Public | BindingFlags.Instance); field.GetValue(reflectionExample);

How do you get a method using Reflection?

Use the GetMethod and GetMethods methods on a Type object. Example Type type = typeof(reflectionExample); MethodInfo methodInfo = type.GetMethod("Multiply"); double returnValue = (double) methodInfo.Invoke(reflectionExample, new object[] { 4, 5 });

How do you get a Property using Reflection?

Use the GetProperty and GetProperties Methods on a Type object.

How do you expose internal types or type members to another assembly?

Use the InternalsVisibleToAttribute. Example [assembly:InternalsVisibleTo("Friend1a")]

How do you get the value from a SecureString object?

Use the Marshal class. Example public static void ConvertToUnsecureStrign(SecureString s) { IntPtr unmanagedString = IntPtr.Zero; try { unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(s); Console.WriteLine(Marshal.PtrToStringUni(unmanagedString)); } finally { Marshal.ZeroFreeGlobalAllocUnicode(unmangedString); } }

How do you spawn a new thread from the ThreadPool?

Use the QueueUserWorkItem method to place a new work item in a queue managed by the thread pool. public static bool QueueUserWorkItem(WaitCallback callback) public delegate void WaitCallback(Object state) Example: ThreadPool.QueueUserWorkItem(new WaitCallback(ExampleMethod));

How do you secure string variables in a program?

Use the SecureString class. Initialize it with single characters so the entire string is not in memory. Example using (SecureString ss = new SecureString()) { Console.Write("Please enter password: "); while(true) { ConsoleKeyInfo cki = Console.ReadKey(true); if(cki.Key == ConsoleKey.Enter) break ss.AppendChar(cki.KeyChar); Console.Write("*"); } ss.MakeReadOnly(); }

How do you create a WCF Web Service?

Use the ServiceContract and OperationContract attributes. The contract is what the outside world expects of your service. Example [ServiceContract] public class MyService { [OperationContract] public string DoWork(string left, string right) { return left + right; } }

How do you use local data in a thread, and initialize it for each thread?

Use the ThreadLocal<T> class. It takes a delegate to a method that initilizes the value. public static ThreadLocal<int> field = new ThreadLocal<int>(() => { return Thread.CurrentThread.ManagedThreadId; }); int value = field.Value ;

How do you provide a custom event accessors?

Use the add and remove accessors. Example private event EventHandler<MyArgs> onChange = delegate { }; public event EventHandler<MyArgs> OnChange { add { lock(onChange) { onChange += value; } } remove { lock(onChange) { onChange -= value; } } }

How do you define a method to be run before or after Serialization?

Use the following attributes a method: [OnSerializing()] [OnSerialized()] [OnDeserializing()] [OnDeserialized()]

How do you specify additional locations where the CLR should look for assemblies?

Use the probing attribute. Can only point to locations relative to the application path. <probing privatePath="MyLibraries" /> Use the codebase element for assembly outside of the application's directory. <codeBase version="1.0.0.0" href="http://www.mydomain.com/ReferencedAssembly.dll" />

How do you define how a thread can have it's own data?

Using the ThreadStatic attribute. [ThreadStatic] public static int field;

How do you serialize an object using Binary Serialization?

Using the [Serializable] attribute. Create a BinaryFormatter object. Create a stream. Send the object and the stream to the BinaryFormatter object. Example IFormatter formatter = new BinaryFormatter(); using (Stream stream = new FileStream("data.bin", FileMode.Create)) { formatter.Serialize(stream, p); }

How do you update the UI from a different thread in a Windows Forms Application?

Utilize the InvokeRequried property and the Invoke method. if(this.InvokeRequired) { this.Invoke(new Action<string>(UpdateLabel), e.Result.ToString()); } else { UpdateLabel(e.Result.ToString()); } private void UpdateLabel(string text) { lblResult.Text = text; }

How do you use LINQ on XML?

Utilize the XDocument class to convert XML to an XDocument object and then use LINQ it's descendants and attributes. Example XDocument doc = XDocument.Parse(xml); IEnumerable<string> names = from p in doc.Descendants("Person") select (string) p.Attribute("firstName") + " " + (string) p.Attribute("lastName");

What types are available in C#?

Value Types Reference Types Pointer Types (Unsafe code only)

What are implicitly typed variables?

Variables where the type is not explictly defined. Example: var m = new MemoryStream();

When would you want to create a value type over a reference type?

When: -The object is small -The object is logically immutable -There are a lot of objects

What are WinMD files? How do you create one?

WinMD (Windows Metadata) files can contain code and metadata to create the correct mapping between native components written in languages that don't have metadata (C++) and other languages. To create one, create a Windows Runtime component in Visual Studio. You should only do this for components that will be used from different programming languages.

What is the XmlDocument class?

XmlDocument is not the fastest option, but the XmlDocument class makes it easier to represent and navigate a Xml document. XmlDocument uses a set of XmlNode objects to represent the various elements comprising the document. Example XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); XmlNodeList nodes = doc.GetElementsByTagName("Person"); foreach(XmlNode node in nodes) { string firstName = node.Attributes["firstName"].Value; }

What is a XmlReader?

XmlReader offers the fastest option of working with XML data. Example using(StringReader sr = new StringReader(xml)) { using(XmlReader xmlReader = XmlReader.Create(sr, new XmlReaderSettings() { IgnoreWhitespace = true})) { xmlReader.MoveToContent(); xmlReader.ReadStartElement("People"); string firstName = xmlReader.GetAttribute("firstName"); } }

What is the yield keyword?

Yield is a keyword that can only be used in the context of iterators. It instructs the compiler to convert this regular code to a state machine. The generated code keeps track of where you are in the collection and it implements methods such as MoveNext and Current. Example public IEnumerator<Person> GetEnumerator() { for(int index = 0; index < people.Length; index++) { yield return people[index]; } }

How do you cancel a Task?

You can pass a CancellationToken to a Task which it monitors to see whether cancellation is requested. Example: CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); CancellationToken token = cancellationTokenSource.Token; Task task = Task.Run(() => { while(!token.IsCancellationRequested) { // Do work } }, token);

How do you create a new value type in C#?

You use the struct keyword to create a new value type.

How do you express a 7 digit phone number as a Regular Expression?

^[2-9][0-9]{2}-\d{4}$

What is a Regular Expression to match a Canadian Postal Code?

^[A-Z]\d[A-Z] \d[A-Z]\d$

How do you create a custom Performance Counter?

if(!PerformanceCounterCategory.Exists("MyCategory")) { CounterCreationDataCollection counters = new CounterCreationDataCollection(); CounterCreationData counter1 = new CounterCreationData(); counter1.CounterName = "Counter1"; counter1.CounterType = PerformanceCounterType.NumberOfItems64; }

How do you define a multi-dimensional array?

int[,] array = new int[3,5];

How do you wait for a Task to be finished?

t.Wait();

How do you read data from a Performance Counter?

using (PerformanceCounter pc = new PerformanceCounter("Memory", "Available Bytes")) { Consolde.Write(pc.RawValue); }

How do you create a new thread?

using System.Threading; public static void ThreadMethod() { } Thread t = new Thread(new ThreadStart(ThreadMethod));

How do you write to a FileStream?

using(FileStream fs = File.Create(path)) { string myValue = "MyValue"; byte[] data = Encoding.UTF8.GetBytes(myValue); fs.Write(data, 0, data.Length); }


Kaugnay na mga set ng pag-aaral

Chapter 20 sun earth and moon study questions.

View Set

Maternity Q&A Review for the NCLEX Questions

View Set

ACCT 5315 Accounting Topics and Managerial Accounting Quizzes Mix

View Set