Saturday, 8 March 2014

c# security review checklist

General Code Review Guidelines

CheckDescription
Ff648189.z02bthcm01(en-us,PandP.10).gifPotential threats are clearly documented. (Threats are dependent upon the specific scenario and assembly type.)
Ff648189.z02bthcm01(en-us,PandP.10).gifCode is developed based on .NET framework coding guidelines and secure coding guidelines at http://msdn.microsoft.com/en-us/library/czefa0ke(VS.71).aspx.
Ff648189.z02bthcm01(en-us,PandP.10).gifThe FXCop analysis tool is run on assemblies and security warnings are addressed.

Managed Code Review Guidelines

Assembly-Level Checks

CheckDescription
Ff648189.z02bthcm01(en-us,PandP.10).gifAssemblies have a strong name. (Dynamically generated ASP.NET Web page assemblies cannot currently have a strong name.)
Ff648189.z02bthcm01(en-us,PandP.10).gifYou have considered delay signing as a way to protect and restrict the private key that is used in the strong name and signing process.
Ff648189.z02bthcm01(en-us,PandP.10).gifAssemblies include declarative security attributes (with SecurityAction.RequestMinimum) to specify minimum permission requirements.
Ff648189.z02bthcm01(en-us,PandP.10).gifHighly privileged assemblies are separated from lower privileged assemblies. If the assembly is to be used in a partial-trust environment (for example, it is called from a partial-trust Web application), then privileged code is sandboxed in a separate assembly.

Class-Level Checks

CheckDescription
Ff648189.z02bthcm01(en-us,PandP.10).gifClass and member visibility is restricted. The most restrictive access modifier is used (private where possible).
Ff648189.z02bthcm01(en-us,PandP.10).gifNon-base classes are sealed if they contain security secrets (like passwords) accessible through protected APIs or if they contain many virtual members that cannot be sealed and the type is not really designed for third-party extensibility.
Ff648189.z02bthcm01(en-us,PandP.10).gifInput from outside the current trust boundary is validated. Input data is constrained and validated for type, length, format, and range.
Ff648189.z02bthcm01(en-us,PandP.10).gifCode implements declarative checks where virtual internal methods are used.
Ff648189.z02bthcm01(en-us,PandP.10).gifAccess to public classes and methods are restricted with principal permission demands (where appropriate).
Ff648189.z02bthcm01(en-us,PandP.10).gifFields are private. When necessary, field values are exposed by using read/write or read-only public properties.
Ff648189.z02bthcm01(en-us,PandP.10).gifRead-only properties are used where possible.
Ff648189.z02bthcm01(en-us,PandP.10).gifTypes returned from methods that are not designed to be created independently contain private default constructors.
Ff648189.z02bthcm01(en-us,PandP.10).gifUnsealed public types do not have internal virtual members.
Ff648189.z02bthcm01(en-us,PandP.10).gifUse of event handlers is thoroughly reviewed.
Ff648189.z02bthcm01(en-us,PandP.10).gifStatic constructors are private.

Cryptography

CheckDescription
Ff648189.z02bthcm01(en-us,PandP.10).gifCode uses platform-provided cryptography and does not use custom implementations.
Ff648189.z02bthcm01(en-us,PandP.10).gifRandom keys are generated by using RNGCryptoServiceProvider (and not the Random class).
Ff648189.z02bthcm01(en-us,PandP.10).gifPasswordDeriveBytes is used for password-based encryption.
Ff648189.z02bthcm01(en-us,PandP.10).gifDPAPI is used to encrypt configuration secrets to avoid the key management issue.
Ff648189.z02bthcm01(en-us,PandP.10).gifThe appropriate key sizes are used for the chosen algorithm, or if they are not, the reasons are identified and understood.
Ff648189.z02bthcm01(en-us,PandP.10).gifKeys are not held in code.
Ff648189.z02bthcm01(en-us,PandP.10).gifAccess to persisted keys is restricted.
Ff648189.z02bthcm01(en-us,PandP.10).gifKeys are cycled periodically.
Ff648189.z02bthcm01(en-us,PandP.10).gifExported private keys are protected.

Secrets

CheckDescription
Ff648189.z02bthcm01(en-us,PandP.10).gifSecrets are not hard coded.
Ff648189.z02bthcm01(en-us,PandP.10).gifPlain text secrets are not stored in configuration files.
Ff648189.z02bthcm01(en-us,PandP.10).gifPlain text secrets are not stored in memory for extended periods of time.

Exception Management

CheckDescription
Ff648189.z02bthcm01(en-us,PandP.10).gifCode uses exception handling. You catch only the exceptions that you know about.
Ff648189.z02bthcm01(en-us,PandP.10).gifException details are logged on the server to assist in diagnosing problems.
Ff648189.z02bthcm01(en-us,PandP.10).gifThe information that is returned to the end user is limited and safe.
Ff648189.z02bthcm01(en-us,PandP.10).gifCode that uses exception filters is not sensitive to filter execution sequence (filter runs before finally block).
Ff648189.z02bthcm01(en-us,PandP.10).gifCode fails early to avoid unnecessary processing that consumes resources.
Ff648189.z02bthcm01(en-us,PandP.10).gifException conditions do not allow a user to bypass security checks to run privileged code.

Delegates

CheckDescription
Ff648189.z02bthcm01(en-us,PandP.10).gifDelegates are not accepted from untrusted sources.
Ff648189.z02bthcm01(en-us,PandP.10).gifIf code does accept a delegate from untrusted code, it constrains the delegate before calling it by using security permissions with SecurityAction.PermitOnly.
Ff648189.z02bthcm01(en-us,PandP.10).gifPermissions are not asserted before calling a delegate.

Serialization

CheckDescription
Ff648189.z02bthcm01(en-us,PandP.10).gifSerialization is restricted to privileged code.
Ff648189.z02bthcm01(en-us,PandP.10).gifSensitive data is not serialized.
Ff648189.z02bthcm01(en-us,PandP.10).gifField data from serialized data streams is validated.
Ff648189.z02bthcm01(en-us,PandP.10).gifISerializable.GetObjectData implementation is protected with an identity permission demand in scenarios where you want to restrict which code can serialize the object.

Threading

CheckDescription
Ff648189.z02bthcm01(en-us,PandP.10).gifResults of security checks are not cached.
Ff648189.z02bthcm01(en-us,PandP.10).gifImpersonation tokens are considered when new threads are created (any existing thread token is not passed to the new thread).
Ff648189.z02bthcm01(en-us,PandP.10).gifThreads are synchronized in static class constructors for multithreaded application code.
Ff648189.z02bthcm01(en-us,PandP.10).gifObject implementation code is designed and built to be thread safe.
Ff648189.z02bthcm01(en-us,PandP.10).gifThreads are synchronized in static class constructors.

Reflection

CheckDescription
Ff648189.z02bthcm01(en-us,PandP.10).gifCaller cannot influence dynamically generated code (for example, by passing assembly and type names as input arguments).
Ff648189.z02bthcm01(en-us,PandP.10).gifCode demands permission for user authorization where assemblies are loaded dynamically.

Unmanaged Code Access

CheckDescription
Ff648189.z02bthcm01(en-us,PandP.10).gifInput and output strings that are passed between managed and unmanaged code are constrained and validated.
Ff648189.z02bthcm01(en-us,PandP.10).gifArray bounds are checked.
Ff648189.z02bthcm01(en-us,PandP.10).gifFile path lengths are checked and do not exceed MAX_PATH.
Ff648189.z02bthcm01(en-us,PandP.10).gifUnmanaged code is compiled with the /GS switch.
Ff648189.z02bthcm01(en-us,PandP.10).gifUse of "dangerous" APIs by unmanaged code is closely inspected. These include LogonUser, RevertToSelf, CreateThread, Network APIs, and Sockets APIs.
Ff648189.z02bthcm01(en-us,PandP.10).gifNaming conventions (safe, native, unsafe) are applied to unmanaged APIs.
Ff648189.z02bthcm01(en-us,PandP.10).gifAssemblies that call unmanaged code specify unmanaged permission requirements using declarative security (SecurityAction.RequestMinimum).
Ff648189.z02bthcm01(en-us,PandP.10).gifUnmanaged API calls are sandboxed and isolated in a wrapper assembly.
Ff648189.z02bthcm01(en-us,PandP.10).gifUse of SuppressUnmanagedCodeSecurityAttribute is thoroughly reviewed and additional security checks are implemented.
Ff648189.z02bthcm01(en-us,PandP.10).gifTypes are not annotated with SuppressUnmanagedCodeSecurityAttribute. (This attribute is used on specific P/Invoke method declarations instead.)
Ff648189.z02bthcm01(en-us,PandP.10).gifCalling code is appropriately authorized using a full stack walk Demand (using either a .NET Framework permission or custom permission).
Ff648189.z02bthcm01(en-us,PandP.10).gifUnmanaged types or handles are never exposed to partially trusted code.
Ff648189.z02bthcm01(en-us,PandP.10).gifPointers are private fields.
Ff648189.z02bthcm01(en-us,PandP.10).gifMethods that use IntPtr fields in a type that has a finalizer call GC.KeepAlive(object).

Resource Access Considerations

File I/O

CheckDescription
Ff648189.z02bthcm01(en-us,PandP.10).gifNo security decisions are made based on filenames.
Ff648189.z02bthcm01(en-us,PandP.10).gifInput file paths and file names are well formed.
Ff648189.z02bthcm01(en-us,PandP.10).gifEnvironment variables are not used to construct file paths.
Ff648189.z02bthcm01(en-us,PandP.10).gifFile access is constrained to the context of the application (by using a restricted FileIOPermission).
Ff648189.z02bthcm01(en-us,PandP.10).gifAssembly file I/O requirements are specified using declarative security attributes (with SecurityAction.RequestMinimum).

Event Log

CheckDescription
Ff648189.z02bthcm01(en-us,PandP.10).gifEvent log access code is constrained using EventLogPermission. This particularly applies if your event logging code could be called by untrusted callers.
Ff648189.z02bthcm01(en-us,PandP.10).gifEvent sources are created at installation time. If unable to create event sources at installation time, the administrator manually creates a new event source entry in the registry. The account used to run the code that writes to the event log is not allowed to create new event sources by configuring ACL in the registry.
Ff648189.z02bthcm01(en-us,PandP.10).gifSecurity-sensitive data, such as passwords, is not written to the event log.

Registry

CheckDescription
Ff648189.z02bthcm01(en-us,PandP.10).gifSensitive data, such as database connection strings or credentials, is encrypted prior to storage in the registry.
Ff648189.z02bthcm01(en-us,PandP.10).gifKeys are restricted. If a key beneath HKEY_CURRENT_MACHINE is used, the key is configured with a restricted ACL. Alternatively, HKEY_CURRENT_USER is used.
Ff648189.z02bthcm01(en-us,PandP.10).gifRegistry access is constrained by using RegistryPermission. This applies especially if your registry access code could be called by untrusted callers.

Environment Variables

CheckDescription
Ff648189.z02bthcm01(en-us,PandP.10).gifCode that accesses environment variables is restricted with EnvironmentPermission. This applies especially if your code can be called by untrusted code.
Ff648189.z02bthcm01(en-us,PandP.10).gifEnvironment permission requirements are declared by using declarative security attributes with SecurityAction.RequestMinimum.

Code Access Security Considerations

If an entry is preceded by a star (*), it indicates that the checks are performed by the FXCop analysis tool. For more information about FXCop security checks, see http://code.msdn.microsoft.com/GotDotNet.aspx.
CheckDescription
Ff648189.z02bthcm01(en-us,PandP.10).gifAssemblies marked with AllowPartiallyTrustedCallersAttribute (APTCA) do not expose objects from non-APTCA assemblies.
Ff648189.z02bthcm01(en-us,PandP.10).gifCode that only supports full-trust callers is strong named or explicitly demands the full-trust permission set.
Ff648189.z02bthcm01(en-us,PandP.10).gifAll uses of Assert are thoroughly reviewed.
Ff648189.z02bthcm01(en-us,PandP.10).gifAll calls to Assert are matched with a corresponding call to RevertAssert.
Ff648189.z02bthcm01(en-us,PandP.10).gif*The Assert window is as small as possible.
Ff648189.z02bthcm01(en-us,PandP.10).gif*Asserts are proceeded with a full permission demand.
Ff648189.z02bthcm01(en-us,PandP.10).gif*Use of Deny or PermitOnly is thoroughly reviewed.
Ff648189.z02bthcm01(en-us,PandP.10).gifAll uses of LinkDemand are thoroughly reviewed. (Why is a LinkDemand and not a full Demand used?)
Ff648189.z02bthcm01(en-us,PandP.10).gifLinkDemands within Interface declarations are matched by LinkDemands on the method implementation.
Ff648189.z02bthcm01(en-us,PandP.10).gif*Unsecured members do not call members protected by a LinkDemand.
Ff648189.z02bthcm01(en-us,PandP.10).gifPermissions are not demanded for resources accessed through the .NET Framework classes.
Ff648189.z02bthcm01(en-us,PandP.10).gifAccess to custom resources (through unmanaged code) is protected with custom code access permissions.
Ff648189.z02bthcm01(en-us,PandP.10).gifAccess to cached data is protected with appropriate permission demands.
Ff648189.z02bthcm01(en-us,PandP.10).gifIf LinkDemands are used on structures, the structures contain explicitly defined constructors.
Ff648189.z02bthcm01(en-us,PandP.10).gif*Methods that override other methods that are protected with LinkDemands also issue the same LinkDemand.
Ff648189.z02bthcm01(en-us,PandP.10).gif*LinkDemands on types are not used to protect access to fields inside those types.
Ff648189.z02bthcm01(en-us,PandP.10).gif*Partially trusted methods call only other partially trusted methods.
Ff648189.z02bthcm01(en-us,PandP.10).gif*Partially trusted types extend only other partially trusted types.
Ff648189.z02bthcm01(en-us,PandP.10).gif*Members that call late bound members have declarative security checks.
Ff648189.z02bthcm01(en-us,PandP.10).gif*Method-level declarative security does not mistakenly override class-level security checks.
Ff648189.z02bthcm01(en-us,PandP.10).gifUse of the following "potentially dangerous" permissions is thoroughly reviewed: SecurityPermission
Unmanaged Code
SkipVerification
ControlEvidence
ControlPolicy
SerializationFormatter
ControlPrincipal
ControlThread
ReflectionPermission
MemberAccess
Ff648189.z02bthcm01(en-us,PandP.10).gifCode identity permission demands are used to authorize calling code in scenarios where you know in advance the range of possible callers (for example, you want to limit calling code to a specific application).
Ff648189.z02bthcm01(en-us,PandP.10).gifPermission demands of the .NET Framework are not duplicated.

C# code review checklist


    1. Are exceptions used to indicate error rather than returning status or error codes?
    2. Are all classes and public methods commented with .NET style comments?  Note that <summary> comments should discuss the "what" of public methods.  Discussion of "how" should be in <remarks> blocks or in-line with the code in question.
    3. Are method arguments validated and rejected with an exception if they are invalid?
    4. Are Debug.Asserts used to verify assumptions about the functioning of the code?  Comments like, "j will be positive" should be rewritten as Asserts. 
    5. Do classes that should not be instantiated have a private constructor?
    6. Are classes declared as value types only infrequently used as method parameters, returned from methods or stored in Collections?
    7. Are classes, methods and events that are specific to an assembly marked as internal?
    8. Are singletons that may be accessed by multiple threads instantiated correctly?  See the Enterprise Solution Patterns book, p. 263.
    9. Are methods that must be overriden by derived classes marked as abstract?
    10. Are classes that should not be overriden marked as sealed?
    11. Is "as" used for possibly incorrect downcasts? 
    12. Do classes override ToString instead of defining a Dump method for outputting the object's state?
    13. Are log messages sent to the logging component instead of Console?
    14. Are finally blocks used for code that must execute following a try? 
    15. Is foreach used in preference to the for(int i...) construct?
    16. Are properties used instead of implementing getter and setter methods?
    17. Are readonly variables used in preference to properties without setters?
    18. Is the override keyword used on all methods that are overriden by derived classes?
    19. Are interface classes used in preference to abstract classes?
    20. Is code written against an interface rather than an implementing class?
    21. Do all objects that represent "real-world" or expensive resources implement the IDisposable pattern?
    22. Are all objects that implement IDisposable instantiated in a using block?
    23. Is the lock keyword used in preference to the Monitor.Enter construct?
    24. Are threads awakened from wait states by events or the Pulse construct, rather than "active" waiting such as Sleep()?
    25. If equals is overridden, is it done correctly?  The rules for overriding equals are complex, see Richter p153-160 for details.
    26. If == and != are overridden, so they redirect to Equals?
    27. Do all objects that override Equals also provide an overloaded version of GetHashCode that provides the same semantics as Equals?  Note that overrides to GetHashCode should take advantage of the object's member variables, and must return an unchanging hash code.
    28. Do all exception classes have a constructor that takes a string and and another constructor that takes a string and an exception?
    29. Do all exception classes derive from the base Matrix exceptions and fit correctly into the exception hierarchy?
    30. Are all classes that will be marshaled or remoted marked with the Serializable attribute?
    31. Do all classes marked with the Serializable attribute have a default constructor?  This includes Exception and EventArgs classes.
    32. Do all classes that explicitly implement ISerializable provide both the required GetObjectData and the implied constructor that takes a SerializationInfo and a StreamingContext?
    33. When doing floating point calculations, are all constants doubles rather than integers?
    34. Do all delegates have a void return type and avoid using output or ref parameters?
    35. Do all delegates send the sender (publisher) as the first argument?  This allows the subscriber to tell which publisher fired the event. 
    36. Are all members of derived EventArg classes read-only?  This prevents one subscriber from modifying the EventArgs, which would affect the other subscribers.
    37. Are delegates published as events?  This prevents the subscribers from firing the event, see Lowy, p. 102 for details.
    38. Is common setup and teardown nUnit code isolated in Setup and Teardown methods that are marked with the appropriate attribute?
    39. Do negative nUnit tests use the ExpectedException attribute to indicate that an exception must be thrown?
     
  1.  
  2. Ensure that there shouldn't be any project warnings.
  3. It will be much better if Code Analysis is performed on a project (with all Microsoft Rules enabled) and then remove the warnings.
  4. All unused usings need to be removed. Code cleanup for unnecessary code is always a good practice.

    Refer to: http://msdn.microsoft.com/en-us/magazine/ee335722.aspx.
     
  5. A "null" check needs to be performed wherever applicable to avoid the Null Reference Exception at runtime.
  6. Naming conventions are to be followed always. Generally for variables/parameters, follow Camel casing and for method names and class names, follow Pascal casing.

    Refer to: http://msdn.microsoft.com/en-us/library/ms229043.aspx.
     
  7. Ensure that you are aware of SOLID principles.

    Definition from Wikipedia: In computer programming, SOLID (Single responsibility, Open-closed, Liskov substitution, Interface segregation and Dependency inversion) is a mnemonic acronym introduced by Michael Feathers for the "first five principles" identified by Robert C. Martin in the early 2000s that stands for five basic principles of object-oriented programming and design. The principles when applied together intend to make it more likely that a programmer will create a system that is easy to maintain and extend over time. The principles of SOLID are guidelines that can be applied while working on software to remove code smells by causing the programmer to refactor the software's source code until it is both legible and extensible. It is typically used with test-driven development, and is part of an overall strategy of agile and adaptive programming.

    Refer to: http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)
     
  8. Code Reusability: Extract a method if the same piece of code is being used more than once or you expect it to be used in the future. Make some generic methods for repetitive tasks and put them in a related class so that other developers start using them once you intimate them. Develop user controls for common functionality so that they can be reused across the project.

    Refer to:

    http://msdn.microsoft.com/en-us/library/office/aa140806(v=office.10).aspx
    o  http://blogs.msdn.com/b/frice/archive/2004/06/11/153709.aspx
     
  9. Code Consistency: Let's say that an Int32 type is coded as an int and a String type is coded as a string, then they should be coded in that same fashion across the application. But not like sometimes an int and sometimes as an Int32.
  10. Code Readability: Should be maintained so that other developers easily understand your code.

    Refer to: http://msdn.microsoft.com/en-IN/library/aa291591(v=vs.100).aspx
     
  11. Disposing of Unmanaged Resources like File I/O, Network resources, etcetera. They must be disposed of once their usage is completed. Use using blocks for unmanaged code, if you want to automatically handle the disposing of objects once they are out of scope.

    Refer to: http://msdn.microsoft.com/en-us/library/498928w2.aspx
     
  12. Proper implementation of Exception Handling (try/catch and finally blocks) and logging of exceptions.

    Refer to: http://msdn.microsoft.com/en-us/library/vstudio/ms229005(v=vs.100).aspx
     
  13. Ensuring that methods have fewer lines of code. Not more than 30 to 40 lines.
  14. Timely check-in/check-out of files/pages at source control (like TFS).

    Refer to: http://www.codeproject.com/Tips/593014/Steps-Check-in-Check-Out-Mechanism-for-TFS-To-avoi
     
  15. Peer code reviews. Swap your code files/pages with your colleagues to perform internal code reviews.
  16. Unit Testing. Write developer test cases and perform unit testing to ensure that a basic level of testing is done before it goes to QA testing.

    Refer to: http://msdn.microsoft.com/en-us/magazine/cc163665.aspx
     
  17. Avoid nested for/foreach loops and nested if conditions as much as possible.
  18. Use anonymous types if code is going to be used only once.

    Refer to: http://msdn.microsoft.com/en-us/library/vstudio/bb397696.aspx
     
  19. Try using LINQ queries and Lambda expressions to improve readability.

    Refer to: http://msdn.microsoft.com/en-us/library/bb308959.aspx 
     
  20. Proper usage of var, object, and dynamic keywords. They have some similarities that cause confusion for developers or don't know much about them and hence they use them interchangeably, which shouldn't be the case.

    Refer to: http://blogs.msdn.com/b/csharpfaq/archive/2010/01/25/what-is-the-difference-between-dynamic-and-object-keywords.aspx
     
  21. Use access specifiers (private, public, protected, internal, protected internal) as per the scope need of a method, a class, or a variable. Let's say if a class is meant to be used only within the assembly, then it is enough to mark the class as internal only.

    Refer to: http://msdn.microsoft.com/en-us/library/kktasw36.aspx
     
  22. Use interfaces wherever needed to maintain decoupling. Some design patterns came into existence due to the usage of interfaces.

    Refer to: http://msdn.microsoft.com/en-IN/library/3b5b8ezk(v=vs.100).aspx
     
  23. Mark a class as sealed or static or abstract as per its usage and your requirements.

    Refer to: http://msdn.microsoft.com/en-us/library/ms173150(v=vs.100).aspx
     
  24. Use a Stringbuilder instead of string if multiple concatenations are required, to save heap memory.
  25. Check whether any unreachable code exists and modify the code if it exists.
  26. Write comments on top of all methods to describe their usage and expected input types and return type information.
  27. Use a tool like Silverlight Spy to check and manipulate rendered XAML in Runtime of a Silverlight application to improve productivity. This saves a lot of back & forth time between Design & Run views of the XAML.
  28. Use the fiddler tool to check the HTTP/network traffic and bandwidth information to trace the performance of web applications and services.
  29. Use the WCFTestClient.exe tool if you want to verify the service methods out of the Visual Studio or by attaching its process to Visual Studio for debugging purposes.
  30. Use constants and readonly wherever applicable.

    Refer to:
    o   http://msdn.microsoft.com/en-us/library/acdd6hb7(v=vs.100).aspx
    o   http://msdn.microsoft.com/en-us/library/e6w8fe1b(v=vs.100).aspx
     
  31. Avoid type casting and type conversions as much as possible; because it is a performance penalty.

    Refer to: http://msdn.microsoft.com/en-us/library/ms173105.aspx
     
  32. Override ToString (from Object class) method for the types that you want to provide with custom information.

    Refer to: http://msdn.microsoft.com/en-us/library/ms173154(v=vs.100).aspx
     
  33. Avoid direct copying/pasting of code from other sources. It is always recommended to hand write the code even though you are referring to the code from some sources. By this, you will get good practice of writing the code yourself and also you will understand the proper usage of that code; finally you will never forget it.
  34. Always make it a practice to read books/articles, upgrade and follow the Best Practices and Guidelines by industry experts like Microsoft experts and well-known authors like Martin Fowler, Kent Beck, Jeffrey Ritcher, Ward Cunningham, Scott Hanselman, Scott Guthrie, Donald E Knuth.
  35. Verify whether your code has any memory leakages. If yes, ensure that they have been fixed.

    Refer to: http://blogs.msdn.com/b/davidklinems/archive/2005/11/16/493580.aspx
     
  36. Try attending technical seminars by experts to be in touch with the latest software trends and technologies and best practices.
  37. Understand thoroughly OOP concepts and try implementing it in your code.
  38. Get to learn your project design and architecture to better understand the flow of your application as a whole.
  39. Take necessary steps to block and avoid any cross scripting attacks, SQL injection, and other security holes.
  40. Always encrypt (using good encryption algorithms) secret/sensitive information like passwords when saving to the database and in connection strings stored in web.config file(s) to avoid manipulation by unauthorized users.
  41. Avoid using the default keyword for the known types (primitive types) like int, decimal, bool, etcetera. It should usually be used with Generic types (T) since we may not be sure whether the type is a value type or reference type. Refer to: http://msdn.microsoft.com/en-us/library/xwth0h0d(v=vs.100).aspx

Wednesday, 5 March 2014

50 LINQ Examples, Tips and How To's

Click to Retweet this link and let fellow developers know about this useful resource
List<T>.ConvertAll<>() with Lambda Expression - List<T> has many useful methods for dealing with sequences and collections. One such method is the ConvertAll<>() method. All those who have used the List<T>.ConvertAll<>() are aware how useful this method is to convert the current List<T> elements to another type, and return a list of converted elements. However, an instance of a conversion delegate must be passed to this method, which knows how to convert each instance from the source type to the destination type
Calculate the Size of a Folder/Directory using .NET 4.0 - .NET 4.0 introduces 7 New methods to Enumerate Directory and Files in .NET 4.0. All these methods return Enumerable Collections (IEnumerable<T>), which perform better than arrays. We will be using the DirectoryInfo.EnumerateDirectories and DirectoryInfo.EnumerateFiles in this sample which returns an enumerable collection of Directory and File information respectively. Here’s how to calculate the size of a folder or directory using .NET 4.0 and LINQ.
LINQ: Generate Odd Numbers using Parallel Execution - A couple of months ago, I had written on Generate Odd Numbers within a Range using LINQ. In that post, I had demoed how to ‘sequentially’ generate odd numbers within a Range. However what if you have to generate a large set of numbers and are not interesting in generating the numbers in a sequence, you can use Parallel Execution
LINQ: Compare two Sequences - How do you compare two sequences using LINQ? The answer is by using the Enumerable.SequenceEqual(). SequenceEqual() compares the source and target sequences elements, by using the default equality comparer for their type, and returns a Boolean.
LINQ: Calculate Average File Size in C# - Let us see a simple code using LINQ and C# that calculates the average FileSize of the files kept in a folder.
LINQ: Generate a Cartesian Product - A Cartesian product by definition is a direct product of two sets. Let us see how to achieve something similar in LINQ using the SelectMany method
LINQ: List Classes implementing the IEnumerable Interface – A reader wanted to know an easy way to find all the types that implement the IEnumerable interface, or for that matter, any interface. Here’s a piece of LINQ code that lists all the types implementing the IEnumerable interface
Find Uppercase words in a String using C# - I am helping a friend to build an Editor API in C#. One of the functionalities in the Editor is to filter uppercase words in a string and highlight them. Here’s a sample of how uppercase words can be filtered in a string
LINQ: Query Comma Separated Value (CSV) files - In this post, we will read a Comma Separated Value (CSV) file using LINQ and perform some calculations on the data.
Generate Odd Numbers within a Range using LINQ - The Enumerable.Range method generates a sequence of integral numbers within a specified range. Here’s how to use it to generate a sequence of odd numbers within a given range say 20 to 40
Generate Sequence of Float Numbers within a Range using LINQ - A small modification to the previous post and use LINQ to generate float numbers within a Range say - 20 to 40.
Query a Sequence using LINQ - In the previous posts, we saw how to Generate Sequence of Float Numbers within a Range using LINQ. In this post, let us see how to query this sequence and extract elements based on a condition
Divide Sequence into Groups and Query using LINQ – In the previous link, I had blogged about Querying a Sequence using LINQ. Now let us say if this sequence was to be divided into smaller sequences/batches and then queried upon, here’s how we would do it using LINQ
LINQ – Left Join Example in C# - In this post, we will see an example of how to do a Left Outer Join in LINQ and C#.
Inner Join Example in LINQ and C# - Let see an example of using the Join method in LINQ and C#. The Join method performs an inner equijoin on two sequences, correlating the elements of these sequences based on matching keys. It is called equijoin, since we are testing for equality using the equals operator.
Using from-let-where Clause in LINQ - In this example, we will see how to use the from-let-where clause in LINQ. For this purpose, let us take a sample array and then print only those numbers in this array, whose square is greater than 10
List all .NET Attributes in the Loaded Assemblies - Here’s how to list all the .NET Attributes in assemblies that are loaded in your application
Rewrite Nested ForEach Loop in LINQ - Let’s assume you have two string array's of the same length and you need to loop through each element of the array and concatenate it’s elements. One way to do this is to use nested foreach loops
Count File Extensions and Group it using LINQ - We have this application where a service reads files generated in a folder every hour and returns a string array containing the file names. A simple report needed to be generated which showed the count of files grouped by the file extension
Swap Words inside a String using LINQ - I was working on a piece of code where the name of the person was stored like “FirstName, LastName”. The requirement was to swap these two words and instead make it look like “LastName, FirstName”
Filter a Type in .NET inside the For-Each Loop - Here’s a nice way to filter an ArrayList right inside the For-Each Loop. We have to filter and print only ‘integers’ greater than 10.
Split a String Collection into Groups using LINQ - I was recently working on an interesting problem which involved splitting a string collection into groups. We had a huge collection of email addresses stored in a string array. The task was to loop the array and select 10 emails at a time and send it for processing
Highest Value in each Group using LINQ - In this post, I will show you how to fetch the maximum value in each Group using LINQ
Loop through Master-Detail Records using LINQ - Here’s an example of how to loop through Master-Detail Records using LINQ. I have taken the example of one Department containing multiple Employees. The example is taken only for the purpose of understanding and does not cover all scenarios.
Concatenate Unique Elements of two List<String> and Sort using LINQ - Here’s how to concatenate unique elements of two List<String> and then Sort them using LINQ
List all Files in .NET 4.0 Based on the Creation Date – A post that shows how to returns a list of files from a directory for a given date range (i.e. start date - end date).
Skip and Select Elements in a String Array using LINQ - Here’s how to skip and select elements in a string array using LINQ. In the example shown below, we will skip the first two elements of an array and select the next three.
Enumerate Hidden Directories in .NET 4.0 - Let us see a practical example of using the DirectoryInfo.EnumerateDirectories to list the names of only hidden directories in a drive
Ordering Elements of a List<String> by Length and Content - Here’s how to order the elements of a List<String> first by length and then by content
Distinct OrderBy in LINQ - One of my colleagues was curious to know how to implement a Distinct-OrderBy on a custom collection in LINQ. Here’s an example. This example uses the Distinct and OrderBy on the CustomerName property of the Customer class.
Using LINQ to select Only Strings from an ArrayList - Here’s a simple example of using LINQ to select only Strings from an ArrayList that contains both integers and strings
Combine Multiple Sequences in LINQ using the Zip Operator - .NET 4.0 - To merge the elements of sequences, use the Zip operator that is new in .NET Framework 4.0
Sort a String Array containing Numbers using LINQ - Here’s how to use LINQ to sort a String Array containing Numbers
Join Two String Arrays with Distinct values using LINQ - One of my colleagues was looking out for a simple way to join two string arrays and avoid duplicates (if any) in those arrays. I asked him to use the Union method which excludes duplicates from the return set.
Using TrueForAll with Generic Lists - If you work with generic lists, you’ll know sometimes you need to check the values in the list to see if they match certain criteria. A method I don’t see used allot is TrueForAll (by Malcolm Sheridan).
Determine all Types that Implement an Interface - I recently saw an interesting discussion on a forum. The discussion was about finding all the types that implement a particular interface. Here’s a code that lists all the types implementing a particular interface
Using LINQ to Find Top 5 Processes that are Consuming Memory - A user on a forum recently asked me how to find the processes that were currently running. A quick look at MSDN led me to the Process object. The Process provides access to local and remote processes and enables you to start and stop local system processes. Here’s how to find out the top five processes that are consuming memory (by Malcolm Sheridan).
Find Distinct Text Using LINQ - Another good use for LINQ popped up today in the forums. The person asked how to get distinct values from a series of text. I once again said LINQ! (by Malcolm Sheridan).
Using LINQ to Search and Delete Old Files - I was recently asked on the asp.net forum about ways to find old files and delete them. I said use LINQ. It is perfect for this scenario.
Using LINQ to Find the Sum of a MultiDimensional Array - Here’s how to the find the sum of a multidimensional array using LINQ. This array has 3 rows and 2 columns
Get Unique Selected Items From Multiple ASP.NET ListBox and Merge them using LINQ - I recently did a short article on Get Selected Items From Multiple ASP.NET ListBox and Merge the results using LINQ. A user pointed out what if you wanted only the unique values from each list. Well here are two options to do that (by Malcolm Sheridan).
How to Sort Data using LINQ - I have been asked allot of questions in the forums lately about LINQ and one question that comes up is how to sort data. A user had an ArrayList of employees and he needed to order them by surname.
Retrieve Selected Items of an ASP.NET ListBox using LINQ - A user ‘JukeBox’ mailed back asking me if it was possible to retrieve the selected items of a ListBox using LINQ. Here’s how to do so
Replicating the 'IN' operator in LINQ - We often use the 'IN' Operator to specify multiple values in the WHERE clause. What if you have to do something similar in LINQ. Here's a simple example that demonstrates this. The example searches out the desired pincodes in a list of Booth Addresses.
Implementing Paging in a Generic List using LINQ - It's quite common of users to bind their Generic List to an ASP.NET control. However if the list is huge, you may need to implement Paging functionality. Here's a simple way to do implement Paging functionality using LINQ
LINQ to XML
LINQ to XML Sorting - In this post, we will read data from the XML file using LINQ to XML, sort it by an element and then load it into a Dictionary.
Serialize XDocument in LINQ To XML - In this post, we will first create an XDocument object that contains XElement objects. You can then serialize the XDocument to a File, XMLWriter or TextWriter
Select Last N elements using LINQ to XML - Here’s a simple example of selecting the last ‘N’ elements of a XML document using LINQ to XML
Create a XML Tree from a String - I got a mail from a devcurry.com reader Martin this morning who asks me “I have a string containing XML tags and I need to create a XML document out of it without much efforts. Is there an easy way to do so. I can assure that the string contains valid xml”. Yes, there is an easy way to do so.
LINQ To XML Tutorials with Examples – A set of 24 examples to teach you LINQ to XML
Hope you found this list useful! Thanks for reading this article.

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...