Google
 

Thursday, June 07, 2007

How design patterns can help you in developing unit testing-enabled applications

REF: http://www.codeproject.com/useritems/DesignPatternsForUnitTest.asp

a few of TDD principles:

  • Do Simple Things: programmers should do the simplest thing that could possibly work.
  • Code Unit Test First: programmers should always code automated tests before coding the functionality that will be tested.
  • Once and Only Once: programmers should sistematically refactor their code to avoid duplication and allow reusability.

  • Some benefits of automated unit tests:

  • Maintainability: Just like the application code, automated unit tests are written in a set of classes, usually maintained in test projects and mapped to the classes to be tested, in an one-by-one basis.
  • Reusability: Automated unit tests can be extended and executed as many times as the development team wishes. Besides, the successful execution of the unit tests can be a requirement for the pre-build phase.
  • Visibility: Unit tests can be used by a code coverage tool so that developers can see how much of the application code has been tested by the unit tests.
  • Developer's Confidence: If a code is properly tested and the automated tests can be easily executed, the developer can refactor or implement new code with much more confidence.
  • Documentation: Unit tests can help extending the class documentation, and providing practical examples of its correct usage.

  • Unfortunately, there are many pitfalls in the path, and the coding unit tests can be a very hard (if not impossible) task, due to bad design choices made by merely applying to new projects the same paradigms of the legacy projects. This is why software architectures should add testability as a requirement for their development cycles.

    It might be said that an application can be deemed easy to be tested if their components (assemblies and classes) are easy to be tested.


    An easy-to-be-tested class is one which can be easily isolated from the other classes it interacts to. That is, we should be able to test a class individually, without having to be concerned with other classes' implementation. Thus, if a unit test fails, it would be much easier to find the source of the bug.

    In unit testing, we isolate the class being tested by creating mocks of the classes it depends on. Mocks are fake instances of a class/interface, and stand for concrete objects. Mocks are critical tools for unit testing isolation.

    This is called "tight coupling", and is a bad design, which hinders the testability of your application, because you will not be able to easily isolate the two classes. Most mock frameworks can't work with tight-coupled classes. Certainly there are tools (like TypeMock) which can do that job.
    Dependency Injection Pattern, also known as Inversion of Control (IoC)

    The Dependency Injection Pattern (a.k.a Inversion of Control)

    InvoiceServices.Test project

    /*
    * Created By HOME
    * User: BPLOVEGCY
    * Date: 2007-6-8
    * Time: 16:12
    *
    *
    http://bplovegcy.blogspot.com/
    *
    */

    using NMock2;
    using NUnit.Framework;
    using System;
    using System.Collections.Generic;
    using System.Text;

    namespace InvoiceServices.Test
    {
    [TestFixture]
    public class InvoiceServicesTest
    {
    [Test]
    public void CalculateInvoiceTest()
    {
    Mockery mockery
    = new Mockery();
    ITaxServices mockTaxServices
    = mockery.NewMock<ITaxServices>();

    InvoiceServices invoiceServices
    = new InvoiceServices(mockTaxServices);

    Expect.Once.On(mockTaxServices).
    Method(
    "CalculateTax").With(100.00F).
    Will(Return.Value(
    5.35F));
    float totalAmount
    = invoiceServices.CalculateInvoice(10001, 10002, 10003);

    //we expect an invoice with product codes 10001, 10002 and 10003
    //to have an amount of $100.00 + a tax amount of $5.35 = $105.35
    float expectedTotalAmount = 105.35F;
    Assert.AreEqual(expectedTotalAmount,
    totalAmount,
    string.Format("Total amount should be {0}",
    expectedTotalAmount.ToString()));
    }
    }
    }

    InvoiceServices project
    /*
    * Created By HOME
    * User: BPLOVEGCY
    * Date: 2007-6-8
    * Time: 16:12
    *
    *
    http://bplovegcy.blogspot.com/
    *
    */
    using System;
    using System.Collections.Generic;

    namespace InvoiceServices
    {
    public class InvoiceServices
    {
    ITaxServices taxServices ;

    public InvoiceServices(ITaxServices tax)
    {
    taxServices
    = tax;
    }

    public float CalculateInvoice(params int[] productCodes)
    {
    float invoiceAmount = 100;
    //Here goes the code to calculate
    //the invoice amount based on products
    return invoiceAmount + taxServices.CalculateTax(invoiceAmount);
    }
    }

    public class TaxServices:ITaxServices
    {
    public TaxServices() { }

    public float CalculateTax(float invoiceAmount)
    {
    float tax = 0;
    // Here goes the code to calculate invoice tax
    return tax;
    }
    }

    public interface ITaxServices
    {
    float CalculateTax(float invoiceAmount);
    }
    }


    The Northwind Solution: putting things together

    The application architecture looks like this:


    The Model-View-Presenter pattern

    To solve this problem, there is a set of design patterns such as Model-View-Controller and Model-View-Presenter. I prefer using the MVP approach because it enhances testability.
    Model: The domain model objects. (e.g. the Customer class)

    The participants of a MVP pattern are:
  • Model: The domain model objects. (e.g. the Customer class)
  • View: A lightweight user interface. (e.g. Windows form)
  • Presenter: A layer coordinationg interaction between the view and the model.

  • Martin Fowler describes the view and presenter components of MVP as Passive View and Supervising Controller. This means that, instead of simply calling the presenter, the view hands off its events to the presenter. Then the view becomes passive, because now the presenter is the responsible for coordinating all presentation logic. Making the view as simple as possible enables us to create automated unit tests on the presentation layer. In addition, there will be very little risk of non-tested view functionality.

    Separated Interface pattern

    Taking a closer look on the interaction between view and presenter in the package diagram below, we'll see that the Northwind sample uses a Separated Interface pattern. The Windows Form named CustomerView implements an ICustomerView interface, which is placed in another assembly (the presenter package). The CustomerPresenter object knows it will have to control a view, but since it holds a reference to the ICustomerView interface, it really doesn't know how the concrete view is going to look like. This pattern is another good design for enabling unit testing, because we'll be able to easily inject a "mocked" view in the presenter, thus performing isolated unit tests on presentation logic.


    Widgets

    The Services layer

    Instead, it should call methods in the Services layer. The Services layer is a good design option, because it exposes well defined processes of the application. Besides, it is a good place where you can define transaction scope, and if you want to implement transactional updates on domain objects, you can implement the Command pattern in Service layer (the Command pattern would enable you to support undoable operations on domain model objects).

    Services layer test results


    The Tranfer Objects layer

    The transfer objects are read-only POCOs (Plain Old C Sharp Objects) that transfer domain model object data between the layers in the application.

    Tranfer Objects layer test results


  • The ActiveRecord attribute provides the table name the domain object is mapped to. This attribute is used by the ActiveRecord framework, an Object-Relational Mapper framework, and will be discussed later on in this article.
  • The MappedTO attribute provides the TransferObject fullname, and is used by the TOHelper class (in the TransferObjects package) in the Domain Object-to-Transfer Object copy operations.

  • The Unit of Work pattern


    The Active Record pattern

    Martin Fowler describes Active Record as

    An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.

    The Castle ActiveRecord was built on top of NHibernate, and provides a powerful, yet simple, set of Object-Relational Mapping functionalities which allows you to persist your domain objects very easily. With Castle ActiveRecord, you can focus on designing your domain model, while saving time working in data access maintainance.

    The Repository pattern

    The last pattern in this article is the Repository pattern. Edward Hieatt and Rob Mee state that the Repository pattern

    Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects








    Wednesday, June 06, 2007

    How to build Sharpdevelop?

    1. Download a copy of Sharpdevelop source code from here
    2. Extract it to your local directory
    3. Install the FxCop and configure the installation path of FxCop with the variable name:FXCOPDIR in System Environment.
    4. Double click the debugbuild.bat or prepareRelease.bat in the src directory of SharpDevelop Source code directory tree.
    5. Now you will build the SharpDevelop successful!

    Installing Subversion from a Zip or Installer File under Windows

    REF: http://svn.collab.net/repos/svn/trunk/INSTALL

    Of all the ways of getting a Subversion client, this is the easiest. Download a Zip (*.zip) or self-extracting installer (*-setup.exe) file from: http://subversion.tigris.org/servlets/ProjectDocumentList?folderID=91 For a Zip file, run your unzipping utility (WinZIP, ZipGenius, UltimateZIP, FreeZIP, whatever) and extract the DLLs and EXEs to a directory of your choice. Included in the download is the SVN client, the SVNADMIN administration tool, and the SVNLOOK reporting tool. Note that if you need support for non-English locales you'll have to set the APR_ICONV_PATH environment variable to the path of the iconv directory in the folder that contains the Subversion install. You may also want to add the bin directory in the Subversion folder to your PATH environment variable so as to not have to use the full path when running Subversion commands. To test the installation, open a DOS box (run either "cmd" or "command" from the Start menu's "Run..." menu option), change to the directory you installed the executables into, and run: C:\test>svn co http://svn.collab.net/repos/svn/trunk svn This will get the latest Subversion sources and put them into the "svn" subdirectory. If using a self-extracting .exe file, just run it instead of unzipping it, to install Subversion.

    Tuesday, June 05, 2007

    What is and how to use Converter Generic Delegate in C#?

    REF:http://msdn2.microsoft.com/en-us/library/kt456a2y.aspx
    Represents a method that converts an object from one type to another type.


    Remarks

    This delegate is used by the ConvertAll method of the Array class and the ConvertAll method of the List class to convert each element of the collection from one type to another.




    What is and how to use System.Action ?

    REF: http://msdn2.microsoft.com/en-us/library/018hxwa8.aspx
    Represents the method that performs an action on the specified object.

    Remarks

    This delegate is used by the Array.ForEach method and the List.ForEach method to perform an action on each element of the array or list.

    The following example demonstrates the use of the Action delegate to print the contents of a List object. In this example, the Print method is used to display the contents of the list to the console.

    NoteNote:

    In addition to displaying the contents using the Print method, the C# example also demonstrates the use of Anonymous Methods (C# Programming Guide) to display the contents to the console.



    using System;
    using System.Collections.Generic;

    class Program
    {
    static void Main()
    {
    List
    <String> names = new List<String>();
    names.Add(
    "Bruce");
    names.Add(
    "Alfred");
    names.Add(
    "Tim");
    names.Add(
    "Richard");

    // Display the contents of the List out using the "Print" delegate.
    Console.WriteLine("Using Action");
    names.ForEach(Print);

    // The following demonstrates the Anonymous Delegate feature of C#
    // to display the contents of the List to the console.
    Console.WriteLine("Using Anonymous Delegate feature");
    names.ForEach(
    delegate(String name){
    Console.WriteLine(name);
    }
    );

    Console.Read();
    }

    private static void Print(string s)
    {
    Console.WriteLine(s);
    }
    }

    Team Development with TFS - Beta 1

    REF: http://www.codeplex.com/TFSGuide/Release/ProjectReleases.aspx?ReleaseId=4442
    Team Development with Visual Studio Team Foundation Guide - PDF Version.
    oc">Click the link below to download the guide.

    TFSGuide.2005-05-22.pdf

    How To Get Started With Web 2.0

    REF: http://www.informationweek.com/shared/printableArticle.jhtml?articleID=199900363

    From wikis to blogs and beyond, here are 10 tips culled from the experts to help you get started building a more dynamic Web site and jumping into Web 2.0.

    By David Strom, InformationWeek
    June 4, 2007
    URL: http://www.informationweek.com/story/showArticle.jhtml?articleID=199900363

    With all the hype over Web 2.0, it's hard to figure out a solid initial strategy to make a corporate Web site more dynamic. Here are our top 10 tips, taken from leading experts and IT managers who already have paved the way. These will help you get your Web 2.0 feet wet and understand the productivity, power, and problems with the genre.

    1
    Start a blog with WordPress or TypePad

    Both sites offer free hosting and simple tools that can take just a few minutes to learn. Both also sell a corporate version of their blogging software (TypePad's is called Movable Type) that can be run from inside a corporate firewall, should that be of concern.

    All blogging software allows for simple creation of Really Simple Syndication data feeds that can be used to keep track of new content and used by collaborative teams to keep each other current with new postings to the site.

    David Meerman Scott, whose latest book is called The New Rules of Marketing And PR (Wiley, 2007), talks about why RSS is so important: "RSS is my preferred method in my work tracking markets, companies, and ideas," he says. "Having the information come to me in my browser as an RSS feed is just so much easier than in the days when I had to go looking for it myself. And it also bypasses the increasingly crowded and annoying e-mail channel, too."

    2
    Start a wiki as your intranet or extranet

    Wikis are Web sites that are easily editable by users, who can change pages and upload their own content. There are free hosting sites such as WetPaint.com, and Jive Software's Clearspace has a hosted version that is free for up to five users and $29 per user per year for larger-scale implementations, with an option to install the software on your own servers.

    "Blogs and wikis are pretty good points of entrance because they are community driven and lightweight," says Eric Raarup, the VP of IT strategy and planning for developer Inetium. "Today's users are creating their own content, responding to content they see on discussion boards, uploading their own documents; that is all part of being in communities of interest." And Scott says "a wiki works well for many organizations as a way to show potential customers that there is a vibrant community of people using their products or services."

    A great example of this is what is happening with Regence, the largest health insurer in the Pacific Northwest/Mountain State region with Blue Cross and Blue Shield Plans in four states. Regence established last year a series of moderated discussion forums covering topics such as parenting, nutrition, and grief issues.

    "We have tapped into Jive technology to involve our members in being active in their own care," says Will McKinney, who is VP of consumer directed health Systems for Regence in Portland, Ore. The company also uses its Interwoven content management system to maintain a series of "live journals" or stories written by real people, using their own names and talking about issues like weight loss, for example. The company also has a team of in-house content editors who travel throughout the region and videotape members' stories to post on the member Web site.

    "We want our members to be engaged and talking among themselves," says McKinney. "Our theme is to reach out to the entire community, involve people beyond chronic diagnoses. It helps to ask the doctor a few questions and make sure they understand your needs. The interest, response, and speed of acceptance happened more quickly that I had thought. Our customers are very anxious to talk and post their thoughts."

    "Wikis can aggregate things for internal consumption very nicely," says David O'Berry, the director of IT for the South Carolina Department of Probation. "They can be used to raise awareness within an organization and help synthesize business knowledge for our subject matter experts."

    "Clearspace can be deployed both inside and outside a corporate firewall," says David Hersh, the CEO of Jive. "It can be used to share ideas and show best corporate practices, and establish communities. We provide a mechanism for organizations who want to have its employees and its customers collaborate. We also have a single architecture and a unified way to start blogs, wikis, and podcasts all at once."

    3
    Pick a Web-friendly database server

    Most of the Web 2.0 technologies involve getting better access, reports, and front-end query interfaces from existing corporate databases. So the best place to start is to choose lightweight projects that can quickly take this information and put it online. "Dabble DB is very Web 2.0 friendly," says Bob Matsuoka, the founder of RunTime Technologies in New York City. "It's a generic object database that works with simple data types, and is very easy to use." You can upload your data in a spreadsheet in a matter of minutes and build a simple application that can cost a few dollars a month to host on their servers, or create a public application for free, according to information on the site.

    You don't need to webify every client/server database, but consider what kinds of databases would benefit if your user had the tools to search the data and create his or her own ad hoc reports. Also consider a mix of public and proprietary data that would benefit your business operations, and how users currently use this data to do their jobs. "One of the things we are dealing with is lowering the barrier of entry -- there is still a lot of custom database and Web programming involved," says Matsuoka. "We act as the glue to connect internal and external data. We also do a lot of development for output to XML, iCal, and other output streams that can be manipulated from our content."

    "You need to consider platforms that will support content that doesn't require IT to be involved in every single part of the site," says Raarup. "As you move to more dynamic content, people are looking for a more personalized experience. Then people feel there is a reason to go to your Web site."

    "The point is all large software companies are moving too slowly," says Matusoka. "The smaller companies, such as ourselves, are doing database integration at the SQL level and creating better front ends for applications and providing links to the back-end databases." He mentions one project where they created Web pages that have an attractive display of a publication's database for one academic client, and they also create the RSS feeds so staffers can more easily keep track of who wrote which papers.

    4
    Learn some Web programming interfaces

    It makes sense to study the leading Web vendors programming tools, such as those freely available from Amazon, Google, and Yahoo, just to name the obvious candidates. These and other places make it easy to start building applications quickly and with minimal cost and effort. They also can be used to combine public data with your private data for what are called mashups.

    "Google Apps are so much easier to use than the equivalent desktop Office products from Microsoft," says Matsuoka. "And once you start using them, you begin to think how you can integrate Google Docs into your corporate workflow. That's their real power: taking private information, using freely available technologies, and providing a repository for this data. For example, a lot of users want to integrate information that they maintain on their desktop calendars or PDAs. So we use iCal feeds to integrate different sets of data."

    5
    Build widgets and components

    Writing to Web 2.0 means not building big applications but starting with smaller projects that can be easily done. Services such as Pageflakes.com or Apatar.com offer various means of connecting different data sources and Web programming interfaces to quickly assemble lightweight applications that can be run inside a Web browser. "You have to starting thinking in the spirit of being an iterative process and not treat your development as one big bundle or a single project," says Raarup.

    Matsuoka suggests that IT developers spend time building widgets that support emerging standards and can be integrated into workspaces attractive to users, such as Apple's Dashboard or Windows Vista's Sidebar, or the public portals such as Yahoo and Google. "Use the public frameworks and APIs and build on top of that. If you don't support how your users work, they'll just find ways to go around you."

    You also should think about reusable components. "Some things you don't have to spend lots of time reinventing, like how someone logs into an application or a database," says O'Berry. "Take what you can in the code and commoditize it -- that gives you the chance to add operational efficiency and cut the costs for future development." O'Berry makes a distinction between these operational efficiencies and making something easy for IT by talking about multifunction printers. Last year he bought 500 desktop printers to make things easier for his users. "I don't want people standing in line to print, scan, or copy something. While it may be easier for the IT organization to have centralized, larger-scale copier/printers, it doesn't make sense for my business. Operational efficiency for IT doesn't always translate into operational efficiency for the business."

    6
    Install interactive Q&A products

    One way to get more traffic and attention to your site and build community is to make use of products that can keep track of questions and answers by visitors. Products such as RightNow Technologies or Wondir.com do a great job of answering your customers' questions, improving customer loyalty, and increasing your company's branding. RightNow is available as a hosted service, while you can add Wondir's service to your site with a few simple lines of code and join its affiliate program to actually make money using its service.

    7
    Exploit social networks

    Social networking sites such as LinkedIn.com, MySpace.com, and Flickr.com have been mostly populated by individual consumers. Businesses, for the most part, have steered clear of them. But a better strategy is to exploit the reputation management that these sites can offer and make use of the viral nature to build brand awareness and track competitors.

    Companies can use these sites when they're recruiting new hires, for example. But less obvious would be to use blogs and social networking sites to talk up new products and to research what the competition is saying about them online.

    "Enterprises are looking to solve problems that start out serving an individual need and then grow and spread virally," says Chuck Neath, general partner at Adams Capital Management. "This new breed of applications require little setup and configuration, deliver immediate value, use social networks, and have minimal impact, if any, on the overall IT organization." BuzzLogic's approach of attaching value to content and participants in social networks is one example, he says. Its on-demand software lets companies manage their brands, products, competitors, and customers within the social media market by measuring influence and identifying key influencers.

    8
    Install better analytics on your site

    Once you know where your visitors are going on your site, you can then concentrate on improving your most-trafficked pages. "Many of the corporate portals that I have seen are pretty sad and built using Web 1.0 technologies with static pages," says Matsuoka. "So most users are going to circumvent them and go to Google or Pageflakes some other public site to organize the information that they want."

    9
    Don't forget about better search techniques

    "You can never spend enough time on improving the search portion of your site," says Raarup. "Search is a powerful way of navigating a site. And given that most people use Google or some other external search tool to find content, your internal site search tools can always stand for some improvement."

    10
    Embrace open source

    Even Microsoft has begun a variety of open source projects, such as its open source project hosting site, CodePlex. And the number of projects that are freely available at such places as IBM's Eclipse, Sourceforge.com, and literally hundreds of other sites continues to grow. The point is that there already is a lot of code out there, free for the asking, even for commercial applications.

    "CodePlex was started by Microsoft for the open source community and is a great source for all sorts of things," says Raarup. "We have posted our own templates for SharePoint user group hosting to the site."

    "The broadest decision you have to make is whether to use Java 2 Enterprise Edition or Microsoft's .Net," says O'Berry. "You have to pick one technology based on your skill set and where your coders could best contribute quickly. But if you chose .Net, as we did, then consider using all open source and free projects and make sure to stay away from choosing anything that requires you to license a large amount of expensive technology. You don't want to get locked in down the road, and you also want to be able to share what you have developed with others, too." O'Berry mentions that his new applications and all of the frameworks will be available for use by departments in other government agencies. "You don't have to be in the same business we're in to benefit from what we have developed. You just have to think about things in a modular and cooperative environment. That goes directly back to commoditized reusable components."

    Taking Smaller Bites

    The wonders of Web 2.0 mean breaking monolithic projects into smaller, more digestible components, and not investing a lot of money or training time in learning and developing. The idea is to build incrementally, learn by doing, and make simple modifications to existing code rather than writing something from start to finish from scratch.

    "What can I do to increase personal productivity savings, while at the same time quantifying the value for my organization?" asks O'Berry. "I want to expand knowledge management for the organization and do it in a way that I can deliver digestible, bite-sized pieces that are relatively quick to code. Ideally, a person should be able to figure out a new application that we build within a minute or two of looking at it."

    What is System.ComponentModel.ISynchronizeInvoke and how to use it?

    Synchronously executes the delegate on the thread that created this object and marshals the call to the creating thread.

    Remarks

    Unlike BeginInvoke, this method operates synchronously, that is, it waits until the process completes before returning. Exceptions raised during the call are propagated back to the caller.

    Use this method when calling a method from a different thread to marshal the call to the proper thread.

    MSDN

    Remarks

    Note:

    The HostProtectionAttribute attribute applied to this class has the following Resources property value: Synchronization | ExternalThreading. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.

    Sample code:



    Monday, June 04, 2007

    What's the meaining of AppDomain?

    Enter the .Net AppDomain

    Conclusion:
    1. Why draw Application Domain concept into .Net?
      1. To improve security of applications
      2. To avoid application crashes caused by memory leak, null object referencing, out of memory boundaries etc.
      3. To avoid applications running in the same process affect each other
    2. What is Application Domain?
      1. The main purpose of an Application Domain is to isolate our applications from other applications. Application domains run on a single Win32 process. The same solution that we just mentioned above can use an application domain and at the same time, limit on the possibility of errors and crashes due to memory leaks.
    3. What's the advantage of it?
      1. Objects in the same Application Domain communicate directly while Objects that exists in different Application Domains interact with each other by transporting copies of objects to each other or by using proxies for message exchange (by reference).
      2. Another advantage of using an Application Domain is that we can destroy it through the host (eg: ASP.Net) without affecting other Application Domains that exist within that Win32 process. Hence our work on the Application Domain can be Independent.
      3. Further, we can also use Application Domains to unload types by destroying the Application Domain that we have loaded it into.
      4. Practically speaking, Application Domains play a critical security and functional role especially when we're creating applications that do remoting like running web services.


    Reading Notes:
    1. Each Win32 process contains at the least one thread (eventually we end up running multiple threads) and if we are to run other tasks or open up other applications through our application, these tasks will belong to our particular Win32 process running on a collection of multiple threads.
    2. One of the characteristics of a Win32 process is that it is very much similar to a virtual boundary.
      1. It's pretty easy to communicate within a process but the same is restricted to a certain level outside that particular Win32 process.
      2. To interact with other Win32 processes, we would require some special mechanisms to work on as there are a couple of security contexts we would have to take into consideration and also the need to restrict what a Win32 process can and should do on a particular system.
    3. Doing so can lead to frequent crashes (oh boy...so used to this part in windows!) where one process using up the memory allocated to another process can lead to unstable environments that eventually…. you know…as usual....just CRASH!
    4. These frequent crashes and run-time errors are usually caused due to inefficient use of memory leading to memory leaks, null object referencing, out of memory bounds and blah blah blah.
    5. Running a host of multiple applications within a single process will enable us to use fewer resources. This would even result to faster execution.
    6. But here's another everyday scenario: incase one application crashes, every other application within this process goes down like a deck of cards!
    7. The main purpose of an Application Domain is to isolate our applications from other applications. Application domains run on a single Win32 process. The same solution that we just mentioned above can use an application domain and at the same time, limit on the possibility of errors and crashes due to memory leaks.
    8. Hence we're running an application within an application domain and we further run multiple application domains within a single Win32 process.
    9. With the CLR's ability to run managed code, we're further cutting down on leaks and crashes (and also thanks to the CLR's Garbage Collector).
    10. Objects in the same Application Domain communicate directly while Objects that exists in different Application Domains interact with each other by transporting copies of objects to each other or by using proxies for message exchange (by reference).
    11. It's actually a pretty neat light weight process that runs within a single Win32 process.
    12. Another advantage of using an Application Domain is that we can destroy it through the host (eg: ASP.Net) without affecting other Application Domains that exist within that Win32 process. Hence our work on the Application Domain can be Independent.
    13. Further, we can also use Application Domains to unload types by destroying the Application Domain that we have loaded it into.
    14. The amazing .Net runtime enforces Application Domain isolation by ensuring control over memory use and therefore all the memory that is used by the Application Domains within a Win32 process is managed by the .Net runtime and therefore we are avoiding all the problems that we mentioned initially such as one application accessing another application's memory and hence avoiding runtime errors followed by crashes.
    15. Hence we're actually using a security layer that isolates current applications from talking to other applications.
    16. Practically speaking, Application Domains play a critical security and functional role especially when we're creating applications that do remoting like running web services.
    17. Inheriting the System.MarshalByRefObject base class into our applications, we can create objects that communicate between and across different application domains.


    .Net Cross AppDomain Communication

    What is and why MarshalByRefObject ?

    REF: MSDN
    Enables access to objects across application domain boundaries in applications that support remoting.

    Namespace: System
    Assembly: mscorlib (in mscorlib.dll)

    Remarks
    Sample 1
    The following code example shows the simplest way to execute code in another application domain. The example defines a class named Worker that inherits MarshalByRefObject, with a method that displays the name of the application domain in which it is executing. The example creates instances of Worker in the default application domain and in a new application domain.
    Note:The assembly that contains Worker must be loaded into both application domains, but it could load other assemblies that would exist only in the new application domain.

    using System;
    using System.Reflection;

    //namespace TestingMarshalObject
    //{

    public class Worker : MarshalByRefObject
    {
    public void PrintDomain(){
    Console.WriteLine(
    "Object is executing in AppDomain \"{0}\"",
    AppDomain.CurrentDomain.FriendlyName);
    }
    }

    public class Example
    {
    /* This code produces output similar to the following:

    Object is executing in AppDomain "source.exe"
    Object is executing in AppDomain "New domain"
    */
    public static void Main(){
    // Create an ordinary instance in the current AppDomain
    Worker localWorker = new Worker();
    localWorker.PrintDomain();

    // Create a new application domain, create an instance
    // of Worker in the application domain, and execute code
    // there.

    // Note: The example and Worker can not be in the same namespace
    // If so the following code will throw exception:
    //Could not load type 'Worker' from assembly 'TestingMarshalObject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

    AppDomain ad
    = AppDomain.CreateDomain("New domain");
    Worker remoteWorker
    = (Worker) ad.CreateInstanceAndUnwrap(
    typeof(Worker).Assembly.FullName,
    typeof(Worker).Name);
    remoteWorker.PrintDomain();

    Console.Read();
    }
    }
    //}



    Sample 2
    The following example demonstrates a class derived from MarshalByRefObject that is used later in remoting.

    using System;
    using System.Runtime.Remoting;
    using System.Security.Permissions;

    public class SetObjectUriForMarshalTest
    {

    class TestClass : MarshalByRefObject
    {
    }

    [SecurityPermission(SecurityAction.LinkDemand)]
    public static void Main()
    {

    TestClass obj
    = new TestClass();

    RemotingServices.SetObjectUriForMarshal(obj,
    "testUri");
    RemotingServices.Marshal(obj);

    Console.WriteLine(RemotingServices.GetObjectUri(obj));

    Console.Read();
    }
    }

    Inheriting from MarshalByRefObject

    Developers often wonder why they are forced to derive from MarshalByRefObject or EnterpriseServices.ServicedComponent. It would be so much more convenient if they could add a CustomAttribute to their class or use a marker interface to declare that they want to be marshaled by reference or they want serviced behavior.

    The reason has to do with performance. The CLR has a large number of optimizations which it can apply to objects that are guaranteed to be local. If the object is possibly remote, then these optimizations are invalidated. Examples include method inlining by the JIT, direct field access, fast instantiation in the local heap, direct method invocation for non-virtuals and more efficient type tests like cast operations.

    When the benefit of these optimizations is considered, it completely outweighs the programming model impact to the inheritance hierarchy. This decision is key to achieving our long term goal of performance parity with native code.


    REF: http://blogs.msdn.com/cbrumme/archive/2003/04/15/51340.aspx

    How to use SuppressMessageAttribute in .Net

    Suppresses reporting of a specific static analysis tool rule violation, allowing multiple suppressions on a single code artifact.


    In Source Suppression Overview

    After reviewing the code, you might determine that the code is correct as is. Or, it might be the case that some violations are of low priority and will not get fixed in the current development cycle. Regardless of the reason, it is often useful to indicate that the warning is non-applicable in order to let the team members know that the code was reviewed and it was determined that the warning be suppressed. In Source Suppression (ISS) is useful because it allows a developer to place the decoration that suppresses the warning close to the warning itself.