Wednesday, July 12, 2017

Top 20 C# Questions

Topics To be Covered 

#1: When to Use a struct vs Class

•structs are value types that can contain data and functions
•structs are value types and do not require heap allocation.
•structs directly store their data in the struct, classes store a reference to a dynamically allocated object.
•structs are useful for small data structures
•structs can affect performance
•Constructors are invoked with the new operator, but that does not allocate memory on the heap
•A struct constructor simply returns the struct value itself (typically in a temporary location on the stack), and this value is then copied as necessary
•With classes, multiple variables may have a reference to the same object
•It is possible for operations on one variable to affect the object referenced by the other variable.
•With structs, the variables each have their own copy of the data, and it is not possible for operations on one to affect the other.
•structs do not support user-specified inheritance, and they implicitly inherit from type object

#2: How would you count the occurrences of a string within a string?

•The string type is a sealed class type that inherits directly from object. Instances of the string class represent Unicode character strings.
•Values of the string type can be written as string literals.
•The keyword string is simply an alias for the predefined class System.String so you can use string name = “Fred”; or String name = “Fred”;
•Likewise you can use string.Concat() or String.Concat()
•Use string for variable names
•Use String for class methods and reference

#3: Encrypt/Decrypt a String in .NET

  • Use C# inbuilt Cryptography Class (DES,RSA etc)

#4: How do I Make a Texbox that Only Accepts Numbers?

  • Use NumericUp Down
  • Handel the KeyPress Event(Text.isDigit )
  • Handel the Text_Changed Event (Not recommended)

#5: How Does One Parse XML Files?

•Reference System.Xml
•Use XmlReader to parse the text string
•You will need to have an idea of the XML elements and attributes for this example
•Use the XmlReader methods to read the XML data

#6: How to Check if a Number is a Power of 2

  • Use Regex or foreach

#7: How do I Get the Index of the Current Iteration of a foreach Loop?

  • Maintain a counter and increment it manually 
  • Some collection type provide IndexOf()

#8: How do I Round a Decimal Value to 2 Places for Output?

•Use string format specifiers
•(“#.##”)
•(“{0:0.00}”, value)
•(“n2”)
•(“{0:c}”, value)

#9: What is the Difference between String and string

•The string type is a sealed class type that inherits directly from object. Instances of the string class represent Unicode character strings.
•Values of the string type can be written as string literals.
•The keyword string is simply an alias for the predefined class System.String so you can use string name = “Fred”; or String name = “Fred”;
•Likewise you can use string.Concat() or String.Concat()
•Use string for variable names
•Use String for class methods and reference

#10: C# Loop — break vs continue

• Break will exit the loop completely, Continue will just skip the current iteration and then test the while statement again.

#11: How to Get My Own IP address in C#

  • check private IP address
  • Use Dns.GetHostEntry , IPAddress and AddressList
  • Ignore APIPA 16.254 starting address
  • Check public IP address- Make External calls 
To Check Public IP address

#12: Remove Duplicates from an Array

•Use LINQ (Use DistinctElement )
•Use a List

#13: How do I get the Application’s Path in a C# Console App?

•Use reflection to get the executing assembly path
•Pass that the IO.Path.GetDirectoryName

#14: Difference Between abstract and virtual functions

  • Abstract Method have no implementation and MUST be overridden
  • Virtual methods MAY have an implementation but are not requireed to and they can be overridden
  • You cannot call base,method() for abstract but you can for virtual methods 

#15: How do I Calculate Someone’s Age in C#?

  • Use Date Time Library built in c#
  • Subtract birthday year from current Year

#16: How do I Sort a Dictionary by Value?

•Use LINQ
•Sorts into a new object

#17: Calling base Constructor in C#

#18: Difference Between ref and out Keywords

  • ref causes an argument to be passed by reference not by value .It provides a reference to the source value and changes made in the method will be made by the source object
  • arguments passed as ref must be initialized before thy are passed 
  • out alos cause the argument to be passed as reference. Changes made to the parameters are also changed in the source
  • Arguments passed out do not have to be initialized first
  • The called method must assign a value prior to the method return

#19: How do I get the String Value of an enum?

  • Use Enum.GetName()
  • USe ToString

#20: How Can I Return Multiple Values From a Function in C#?

•Using out parameters
•Using arrays or structs
  • Consider finding min and max values in an array

Sunday, July 09, 2017

Notes :Programming in C# Jump Start ( Microsoft Exam-70-483)

Module 1:

Object orineted Programing ; Managed Language & C#

What is Object Oriented Programming
To be object oriented, a language is designed around the concept of objects. that are something, have certain properties and exhibit certain behaviors. This means the language generally includes support for: —
Encapsulation — Inheritance — Polymorphism
What is Managed Language
Managed languages depend on services provided by a runtime environment.
• C# is one of many languages that compile into managed code.
• Managed code is executed by the Common Language Runtime (CLR).
• The CLR provides features such as: — Automatic memory management — Exception Handling — Standard Types — Security
There are 3 categories of types:
— Value types : these directly store values
— Reference types:or objects, store a reference to data
— Pointer types:only available in unsafe code
What are Lambda Expressions
  • An enhancement of anonymous methods
  • • An unnamed method written inline
  • • An alternative to a delegate
  • • At compile time a lambda expression becomes either: — An instance of a delegate — Or an expression tree
  • • Expressions are validated at compile time, but evaluated at run time.
  • • Dynamic expression trees are supported

Module 2:

Constructing Complex Types, Object Interfaces and Inheritance and Generics

Classes and Structs
• A class or struct defines the template for an object.
  • A class represents a reference type
  • A struct represents a value type
  • Reference and value imply memory strategies
When to Use Structs :
Use structs if:
— instances of the type are small
— the struct is commonly embedded in another type
— the struct logically represent a single value
— the values don’t change (immutable)
— It is rarely “boxed” (see later)
• Note: structs can have performance benefits in computational intensive applications
Note : Useful : 2 classes inside same namespace

Inheritance

— Classes can optionally be declared as:
  1. static — can never be instantiated
  2. abstract — can never be instantiated; it is an incomplete class
  3. sealed — all classes can be inherited unless marked as sealed
— Virtual Methods
  1. Virtual methods have implementations
  2. They can be overridden in derived class.

What are Virtual Functions

Virtual Function is a function in base class, which is overrided in the derived class, and which tells the compiler to perform Late Binding on this function.
Virtual Keyword is used to make a member function of the base class Virtual.
Example :
difference between genric and collection

Module 3:

Controlling Programmatic Flow & Manipulating Types and Strings

Module 4:

Code Reflection and Information ,Working with Garbage Collection

What is Reflection
Reflection inspects type metadata at runtime
The type metadata contains information such as:
  1. The type Name
  2. The containing Assembly
  3. Constructors
  4. Properties
  5. Methds
  6. Attributes
  • This data can be used to create instances, access values and execute methods dynamically at runtime
What is Garbage Collection
Garbage collection is automatic memory management.
• De-referenced objects (orphans) are not collected immediately but periodically.
  • factors influence Garbage Collection frequency —
  • Not all orphans are collected at the same time
Garbage Collection is computationally expensive

Memory Leaks

  • Despite having automatic memory management, it is still possible to create managed memory leaks.
  • • Objects that fall out of scope may be referenced by objects in scope, keeping them alive.
  • • Events can be a common source of memory leaks:Events can hold references to objects ,Solution! Unsubscribe from events proactively
  • • Weak references can be used to avoid some memory leak scenarios

Weak Reference

  • Weak references create a reference that the Garbage Collector ignores.
  • • The Garbage Collector will assume an object is eligible for collection if it is only referred to by weak references.
  • • To hold an object with only weak references, create a local variable referring to the weak reference value.
— This prevents collection until the local variable is out of scope.

Module 5:

Type and Value Validation , Encryption Technique

What is Data Validation
  • Data validation is testing values introduced to an app (via a service, file, or data entry) against expected values and ranges.
  1. Prevent overflow
  2. Prevent incorrect results
  3. Prevent undesirable side-effects
  4. Provide guidance to systems or users
  5. Prevent security intrusions
The compiler validates that the object type is correct — It does not validate the object’s value
  • Debug / Trace Assert() methods alert the developer or the user
  • Raise an Exception:
— System.ArgumentException
— System.ArgumentOutofRangeException
— System.ArgumentNullException

Data Contracts

  • “Design by Contract” from the Eiffel programming language
  • Code contracts are a unified system that can replace all other approaches to data validation
  • Code contracts have — Preconditions (Requires) — Post-conditions (Ensures)
  • A contract assertion can be “evaluated” statically
  • A contract assertion can be “enforced” at runtime

What is Encryption

  • An encryption algorithm makes data unreadable to any person or system until the associated decryption algorithm is applied.
— Encryption does not hide data; it makes it unreadable
— Encryption is not the same as compression
  • Types of encryption
— File Encryption
— Windows Data Protection
— Hashing, used for signing and validating
— Symmetric and Asymmetric

Simple Encryption Mehtods

  • File Encryption
— Encrypts and decrypts files
— Fast to encrypt/decrypt
— Based on user credentials
  • Windows Data Protection
— Encrypts and decrypts byte[]
— Fast to encrypt/decrypt
— Based on user credentials

Hashing

One-way encryption
• Common algorithms:
— MD5 (generates a 16 character hash than can be stored in a Guid)
— SHA (SHA1, SHA256, SHA384, SHA512)
Fast (depending on chosen algorithm)
  • Used for storing passwords, comparing files, data corruption/tamper checking — Use SHA256 or greater for passwords or other sensitive data

Symmetric Encryption

  • One key is used for both encryption and decryption
  • Faster than asymmetric encryption
• Cryptography namespace includes five symmetric algorithms:
— Aes (recommended)
— DES
— RC2
— Rijndael
— TripleDES

Asymmetric (or Public Key) Encryption

  • One key is used for encryption and another key for decryption
  • Commonly used for digital signatures
  • Cryptography namespace includes four asymmetric algorithms:
— DSA
— ECDiffieHellman
— ECDsa
— RSA (most popular)

Module 6:

Splitting Assemblies and Projects , Diagnostics and Instrumentation

What is an assembly?
  • An assembly is a container for a set of resources and types.
  • Assemblies can be referenced by other assemblies.
  • Some assemblies are specific to certain technologies.
  • In Visual Studio, an assembly equates to a Project
What is Instrumentation?
  • Instrumentation is code that reports performance information.
  • Telemetry aggregates instrumentation for analysis.
  • Diagnostics or Analysis is the use a telemetry to track causes of errors or identify trends.
What is a Performance Counter?
  • Performance Counter is a sampling for a single operation
  • You write to a counter by incrementing or decrementing
— Trending is accomplished using tooling
• You must have permission
• Counters are typically categorized

Module 7:

Interacting with File System, Working With REST Services

Why read or write to the file system?
  • Show existing data to user
  • Integrate user-provided data
  • Serialize objects out of memory
  • Persist data across sessions
  • Determine environment configuration

How do we write to files?

  • This is simplified with Framework methods; open / shut — File.WriteAllText / ReadAllText
  • Open for reading to keep open and keep writing
  • Open as stream for large payloads and realtime processing
How do we find files?
  • Get Windows folder with Environment Special Folders
  • Get the Current folder with File.IO Get Current Directory()
  • Use Isolated Storage dedicated to the current application
  • Anything Else. Caveat: Windows Store App development
How do we modify files?
  • Iterate through files using GetFiles()
  • Rename / Move with System.IO methods
  • Get File Info with System.UI.FileInf
What are Web Services?
  • Web Services encapsulate implementation
  • Web Services expose to disparate system
  • Web Services allow client systems to communicate servers — Web protocols (HTTP, GET, POST, etc)
  • Web Services are important to Service Oriented Architecture
— With and without metadata
— Loose coupling
What is SOAP?
  • SOAP is a standard for returning structured data from a Web Service as XML
— Envelope
— — — Header
— — —Bod
What is asynchronous programming ?
  • Asynchronous maximizes resources on multicore systems, by allowing units of work to be separated and completed.
  • Asynchronous programming frees up the calling system, especially a user interface, as to not wait for long operations.
What is the C# ASYNC/AWAIT keywords
  • Async and await simplify asynchronous programming.
  • Async and await allow asynchronous code to resemble the structure of synchronous code.
  • Methods marked with async may return Task<T>.
  • The async keyword instructs the compiler to allow await.
  • The await keyword instructs the method to return.
  • The await keyword instructs the compiler to resume execution within the same context after the operation is complete

Module 8:

Accessing a Database , Using LINQ

(More Notes on C# to JSON)
What databases can we use?
  • Windows Azure SQL Database
  • Local Network SQL Server
  • Local Machine SQL Server Express
  • Application SQL LocalDB
  • Application SQL CE
  • Other providers: Oracle, SqLite, MySql, DB2, Jet
— ADO.Net implements a provider model enabling many (if not all) databases. Database implementation is abstracted.
Types of access to a database
  • Low-level — Manual queries — DbDataReader
  • Object Relationship Models (ORM)
— Conceptual Modelling
— Entity Framework, Nhibernate, CSLA, Dapper
What is Language Integrated Query
  • LINQ is a general-purpose Query Language
  • LINQ is an integrated part of the .Net languages
  • LINQ is Type Safe and has Intellisense
  • LINQ includes operators like Traversal, Filter, and Projection
  • LINQ can be optimized with compiler versions
  • LINQ can be invoked using its Query Syntax
  • LINQ can be invoked using its Method Syntax
Reference :