2013년 1월 31일 목요일

how to sharepoint list file download


how to sharepoint list file download


Hi All,

In this post, I will show you the way how to get the list attachments using SharePoint web services. There can be one or more attachment attached to the list item of any list in the site.

For example, I have one Dummy List in the site and I have one list item with two attachments. See the figure below.



Now write down the following code. DownloadListItems is the lists.asmx web service of SharePoint. Change the site url reference for your code.

private void button8_Click(object sender, EventArgs e)
{
DownloadListItems.Lists objLists = new EncryptAndDecrypt.DownloadListItems.Lists();

objLists.Credentials = System.Net.CredentialCache.DefaultCredentials;

objLists.Url = "{site-url}/_vti_bin/lists.asmx";

XmlNode node = objLists.GetAttachmentCollection("DummyList", "7");

DataSet ds = new DataSet();
using (XmlNodeReader reader = new XmlNodeReader(node))
{
ds.ReadXml(reader);
}


DataTable dtAttachment = ds.Tables[0];

for (int iCnt = 0; iCnt <= dtAttachment.Rows.Count - 1; iCnt++)
{
string sourceUrl = Convert.ToString(dtAttachment.Rows[iCnt]["Attachment_Text"]);

int strLastIndx = sourceUrl.LastIndexOf(@"/");

string FileName = sourceUrl.Substring(strLastIndx + 1);


using (WebClient client = new WebClient())
{
client.UseDefaultCredentials = true;
byte[] response = client.DownloadData(sourceUrl);

FileStream fStream = new FileStream(@"C:\DummyListAttachments\" + FileName, FileMode.Create, FileAccess.ReadWrite);
fStream.Write(response, 0, response.Length);
fStream.Close();

}


}


}


As you can see first we have taken the reference of the Lists.asmx service and then passed the credentials. Change it to your credentials according to your need. Then we called getattachmentcollection method, and simple got the attachments in the form of XMLNode. 

We actually get path only, not the real attachments. For simplicity I have converted that XMlnode into to data table so that we get the Attachment table and attachment_xml column with values as direct path to the attachment with complete URL of the site.



And then finally we use WebClient method to pull those documents to our local drive.

Very simple and easy way to get the attachments from list item. What say?

http://www.sharepointkings.com/2010/05/download-attachments-from-list-item.html

How To: Add an attachment to an Outlook e-mail message

How To: Add an attachment to an Outlook e-mail message



C# and Add-in Express:
private void AddAttachmentFromFile(Outlook._Application OutlookApp) 
    Outlook.Inspector activeInspector = OutlookApp.ActiveInspector(); 
    if (activeInspector != null
    { 
        Outlook.MailItem activeMailItem = activeInspector.CurrentItem as Outlook.MailItem; 
        if (activeMailItem != null
        { 
            Outlook.Attachments mailAttachments = activeMailItem.Attachments; 
            // the last two arguments can be applied if the Rich Text format is used 
            Outlook.Attachment newAttachment = mailAttachments.Add( 
                @"C:\Text Document.txt", Outlook.OlAttachmentType.olByValue, 
                1, "The test attachment"); 
            activeMailItem.Save(); 
            // don't forget to release underlying COM objects 
            if (newAttachment != null) Marshal.ReleaseComObject(newAttachment); 
            if (mailAttachments != null) Marshal.ReleaseComObject(mailAttachments); 
            Marshal.ReleaseComObject(activeMailItem); 
        } 
        Marshal.ReleaseComObject(activeInspector); 
    } 
VB.NET and Add-in Express:
Private Sub AddAttachmentFromFile(OutlookApp As Outlook._Application) 
    Dim activeInspector As Outlook.Inspector = OutlookApp.ActiveInspector() 
    If Not IsNothing(activeInspector) Then 
        Dim activeMailItem As Outlook.MailItem = activeInspector.CurrentItem 
        If Not IsNothing(activeMailItem) Then 
            Dim mailAttachments As Outlook.Attachments = activeMailItem.Attachments 
            ' the last two arguments can be applied if the Rich Text format is used 
            Dim newAttachment As Outlook.Attachment = mailAttachments.Add( _ 
                "C:\Text Document.txt", Outlook.OlAttachmentType.olByValue, _ 
                 1, "The test attachment"
            activeMailItem.Save() 
            ' don't forget to release underlying COM objects 
            If Not IsNothing(newAttachment) Then 
                Marshal.ReleaseComObject(newAttachment) 
            End If 
            If Not IsNothing(mailAttachments) Then 
                Marshal.ReleaseComObject(mailAttachments) 
            End If 
            Marshal.ReleaseComObject(activeMailItem) 
        End If 
        Marshal.ReleaseComObject(activeInspector) 
    End If 
End Sub 
C# and VSTO:
using System.Runtime.InteropServices; 
// ... 
private void AddAttachmentFromFile(Outlook.Application Application) 
    Outlook.Inspector activeInspector = Application.ActiveInspector(); 
    if (activeInspector != null
    { 
        Outlook.MailItem activeMailItem = activeInspector.CurrentItem as Outlook.MailItem; 
        if (activeMailItem != null
        { 
            Outlook.Attachments mailAttachments = activeMailItem.Attachments; 
            // the last two arguments can be applied if the Rich Text format is used 
            Outlook.Attachment newAttachment = mailAttachments.Add( 
               @"C:\Text Document.txt", Outlook.OlAttachmentType.olByValue, 
               1, "The test attachment"); 
            activeMailItem.Save(); 
            // don't forget to release underlying COM objects 
            if (newAttachment != null) Marshal.ReleaseComObject(newAttachment); 
            if (mailAttachments != null) Marshal.ReleaseComObject(mailAttachments); 
            Marshal.ReleaseComObject(activeMailItem); 
         } 
         Marshal.ReleaseComObject(activeInspector); 
     } 
VB.NET and VSTO:
Imports System.Runtime.InteropServices 
' ... 
Private Sub AddAttachmentFromFile(Application As Outlook.Application) 
    Dim activeInspector As Outlook.Inspector = Application.ActiveInspector() 
    If Not IsNothing(activeInspector) Then 
        Dim activeMailItem As Outlook.MailItem = activeInspector.CurrentItem 
        If Not IsNothing(activeMailItem) Then 
            Dim mailAttachments As Outlook.Attachments = activeMailItem.Attachments 
            ' the last two arguments can be applied if the Rich Text format is used 
            Dim newAttachment As Outlook.Attachment = mailAttachments.Add( _ 
                "C:\Text Document.txt", Outlook.OlAttachmentType.olByValue, _ 
                1, "The test attachment"
            activeMailItem.Save() 
            ' don't forget to release underlying COM objects 
            If Not IsNothing(newAttachment) Then 
                Marshal.ReleaseComObject(newAttachment) 
            End If 
            If Not IsNothing(mailAttachments) Then 
                Marshal.ReleaseComObject(mailAttachments) 
            End If 
            Marshal.ReleaseComObject(activeMailItem) 
        End If 
        Marshal.ReleaseComObject(activeInspector) 
    End If 
End Sub 
See you on our forums and in the e-mail support!




http://www.add-in-express.com/creating-addins-blog/2011/08/12/how-to-add-existing-e-mail-message-as-attachment/
http://www.add-in-express.com/creating-addins-blog/2011/08/10/how-to-add-attachment-to-e-mail-message/

sharepoint lists.asmx get all folders


sharepoint lists.asmx get all folders
Getting all items in folders using the Lists.asmx Web Service


private string DocumentReturnString(DiCentralSharePointWs.Lists ListsWebService, string listName)
{
        System.Xml.XmlNode nodes;
        string value = string.Empty;
        try
        {
            XmlDocument xmlDoc = new XmlDocument();
            XmlNode query = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
            XmlNode queryOptions = xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", "");
            queryOptions.InnerXml = "<ViewAttributes Scope='RecursiveAll' />";

            nodes = ListsWebService.GetListItems(listName, null, null, null, null, queryOptions, null);            
        }
        catch
        {
            return string.Empty;
        }

        foreach (XmlNode outerNode in nodes.ChildNodes)
        {

            if (outerNode.NodeType.Equals(System.Xml.XmlNodeType.Element))
            {

                foreach (XmlNode node in outerNode.ChildNodes)
                {

                    if (node.NodeType.Equals(System.Xml.XmlNodeType.Element))
                    {
                        string fileName = node.Attributes.GetNamedItem("ows_FileLeafRef").Value.Split(new string[] { ";#" }, StringSplitOptions.None)[1].ToString(); ;
                        string filePath = node.Attributes.GetNamedItem("ows_FileRef").Value.Split(new string[] { ";#" }, StringSplitOptions.None)[1].ToString(); ;
                        string fullPath = HttpUtility.UrlPathEncode(txtSiteURL.Text + filePath);
                        value += "<a href=" + fullPath + ">" + fileName + "</a>" + "</br>";
                    }

                }

            }

        } 
        return value;
}

2013년 1월 30일 수요일

sharepoint client model custom list folder file attach

SharePoint 2010 - Client Object Model - Add attachment to ListItem


I struggled for a long time with this problem too, so I thought I'd post a complete code sample showing how to successfully create a list item and add an attachment.
I am using the Client Object API to create the list item, and the SOAP web service to add the attachment. This is because, as noted in other places on the web, the Client Object API can only be used to add attachments to an item where the item's upload directory already exists (eg. if the item already has an attachment). Else it fails with a 409 error or something. The SOAP web service copes with this OK though.
Note that another thing I had to overcome was that even though I added the SOAP reference using the following URL:
The URL that VS actually added to the app.config was:
I had to manually change the app.config back to the correct URL, else I would get the error:
List does not exist. The page you selected contains a list that does not exist. It may have been deleted by another user. 0x82000006
Here is the code:
    void CreateWithAttachment()
    {
        const string listName = "CodeReviews";
        // set up our credentials
        var credentials = new NetworkCredential("username", "password", "domain");

        // create a soap client
        var soapClient = new ListsService.Lists();
        soapClient.Credentials = credentials;

        // var create a client context
        var clientContext = new Microsoft.SharePoint.Client.ClientContext("https://my.sharepoint.installation/personal/test");
        clientContext.Credentials = credentials;

        // create a list item
        var list = clientContext.Web.Lists.GetByTitle(listName);
        var itemCreateInfo = new ListItemCreationInformation();
        var newItem = list.AddItem(itemCreateInfo);

        // set its properties
        newItem["Title"] = "Created from Client API";
        newItem["Status"] = "New";
        newItem["_Comments"] = "here are some comments!!";

        // commit it
        newItem.Update();
        clientContext.ExecuteQuery();

        // load back the created item so its ID field is available for use below
        clientContext.Load(newItem);
        clientContext.ExecuteQuery();

        // use the soap client to add the attachment
        const string path = @"c:\temp\test.txt";
        soapClient.AddAttachment(listName, newItem["ID"].ToString(), Path.GetFileName(path),
                                  System.IO.File.ReadAllBytes(path));
    }
Hope this helps someone.


http://msdn.microsoft.com/en-us/library/websvclists.lists.addattachment.aspx

http://stackoverflow.com/questions/2969810/sharepoint-2010-client-object-model-add-attachment-to-listitem

WCF Per-Call Service


Per-Call Service

When WCF service is configured for Per-Call instance mode, Service instance will be created for each client request. This Service instance will be disposed after response is sent back to client.
Following diagram represent the process of handling the request from client using Per-Call instance mode.
Let as understand the per-call instance mode using example.
Step 1: Create the service contract called IMyService and implement the interface. Add service behavior attribute to the service class and set the InstanceContextMode property to PerCall as show below.
    [ServiceContract()]
    public interface IMyService
    {
        [OperationContract]
        int MyMethod();
    }
Step 2: In this implementation of MyMethod operation, increment the static variable(m_Counter). Each time while making call to the service, m_Counter variable is incremented and return the value to the client.
    [ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]
    public class MyService:IMyService
    {
        static int m_Counter = 0;

        public int MyMethod()
        {
            m_Counter++;
            return m_Counter;
        }       
    }
 
Step 3: Client side, create the proxy for the service and call "myMethod" operation multiple time.
        static void Main(string[] args)
        {
            Console.WriteLine("Service Instance mode: Per-Call");
            Console.WriteLine("Client  making call to service...");
            //Creating the proxy on client side
            MyCalculatorServiceProxy.MyServiceProxy proxy =
             new MyCalculatorServiceProxy.MyServiceProxy();
            Console.WriteLine("Counter: " + proxy.MyMethod());
            Console.WriteLine("Counter: " + proxy.MyMethod());
            Console.WriteLine("Counter: " + proxy.MyMethod());
            Console.WriteLine("Counter: " + proxy.MyMethod());
            Console.ReadLine();
}
Surprisingly, all requests to service return '1', because we configured the Instance mode to Per-Call. Service instance will created for each request and value of static variable will be set to one. While return back, service instance will be disposed. Output is shown below.
Fig: PercallOutput.

Building and Accessing Duplex Services


Building and Accessing Duplex Services

Silverlight
4 out of 5 rated this helpful Rate this topic
Duplex communication allows either the Windows Communication Foundation (WCF) service or the Silverlight version 4 client to initiate a message exchange, in contrast to the more commonly used request-reply pattern where the Silverlight 4 client always initiates the message exchange. Duplex messaging (also referred to as a "server push") is useful when the server needs to notify the client of new information asynchronously, for example, to notify of the arrival of a new chat or e-mail message.
WCF offers a way to model duplex services that abstracts away the specific duplex transport that is being used. You write your service once, and then change the transport depending on the requirements of your particular scenario. On the other hand, Silverlight 4 offers duplex services with models that are tied to either an HTTP- or a TCP-based duplex transport.
Duplex communication over HTTP: A Silverlight 4 client is not addressable over HTTP because the browser environment does not allow the creation of an HTTP listener. HTTP duplex communication with a Silverlight 4 client is achieved by having the client poll a destination server for messages from within an established session. The server will return a chunked HTTP response with as many messages as are currently pending, and then close the poll response. In addition to HTTP, two protocols are used by the Silverlight 4 polling duplex feature. The Net Duplex Protocol is implemented to establish the client session with a server, and the WS-Make Connection (WS-MC) Protocol uses polling to establish a back channel that enables server-initiated messages to be delivered to the client. This HTTP-based functionality is available in the system-providedPollingDuplexHttpBinding.
Cc645026.security(en-us,VS.95).gif Security Note:
The polling duplex server listens on the standard HTTP port 80 so it is not typically blocked by firewalls.
Duplex communication over TCP: A sockets-networking API that works over the TCP protocol is also provided by Silverlight 4. This allows Silverlight 4 clients to open a bi-directional TCP connection to a server and implement duplex messaging over that connection. The Silverlight 4 sockets API is subjected to several security restrictions, specifically the need for the server to expose a policy file for both site-of-origin and cross-domain scenarios, and also for the restricted range of ports that can be used on the server. In out-of-browser elevated applications, some of these requirements can be relaxed. For more information about sockets and how to configure your server for sockets access, see Working with Sockets.
WCF services enable duplex communication over TCP sockets with Silverlight clients through a NetTcpBinding with security turned off.
Cc645026.security(en-us,VS.95).gif Security Note:
Silverlight 4 does not support NetTcpBinding with security. Any information you send using this binding configuration is unencrypted and can be intercepted and modified by unauthorized third parties. Do not send sensitive information using this binding configuration.
Using the Add Service Reference tool to generate the client when the duplex service is configured with the NetTcpBinding results in the client being configured with a NetTcp binding.
Both Silverlight 4 and WCF use the .NET Message Framing Protocol to negotiate the exchange of SOAP messages over a TCP connection. For additional information about this protocol, see .NET Message Framing Protocol Specification.
Cc645026.security(en-us,VS.95).gif Security Note:
Running services that can be accessed by TCP sockets with Silverlight 4 clients may require configuration changes to your firewall.

In This Section

How to: Build a Duplex Service for a Silverlight Client
Describes how to create a Silverlight-enabled WCF duplex service that can communicate with a Silverlight client.
How to: Access a Duplex Service
Describes how to create a Silverlight client that can communicate with a Silverlight-enabled WCF duplex service.

Reference

2013년 1월 29일 화요일

Shim types

Shim types



Using shims to isolate your application from other assemblies for unit testing

Visual Studio 2012
5 out of 10 rated this helpful Rate this topic
Shim types are one of two technologies that the Microsoft Fakes Framework uses to let you easily isolate components under test from the environment. Shims divert calls to specific methods to code that you write as part of your test. Many methods return different results dependent on external conditions, but a shim is under the control of your test and can return consistent results at every call. This makes your tests much easier to write.
Use shims to isolate your code from assemblies that are not part of your solution. To isolate components of your solution from each other, we recommend that you use stubs.
For an overview and quick start guidance, see Isolating Code under Test with Microsoft Fakes
Requirements
  • Visual Studio Ultimate
Let’s consider a method that throws an exception on January 1st of 2000:
// code under test
public static class Y2KChecker {
    public static void Check() {
        if (DateTime.Now == new DateTime(2000, 1, 1))
            throw new ApplicationException("y2kbug!");
    }
}
Testing this method is particularly problematic because the program depends on DateTime.Now, a method that depends on the computer's clock, an environment-dependent, non-deterministic method. Furthermore, the DateTime.Now is a static property so a stub type can’t be used here. This problem is symptomatic of the isolation issue in unit testing: programs that directly call into database APIs, communicate with web services, and so on are hard to unit test because their logic depends on the environment.
This is where shim types should be used. Shim types provide a mechanism to detour any .NET method to a user defined delegate. Shim types are code-generated by the Fakes generator, and they use delegates, which we call shim types, to specify the new method implementations.
The following test shows how to use the shim type, ShimDateTime, to provide a custom implementation of DateTime.Now:
//unit test code
// create a ShimsContext cleans up shims 
using (ShimsContext.Create()
    // hook delegate to the shim method to redirect DateTime.Now
    // to return January 1st of 2000
    ShimDateTime.NowGet = () => new DateTime(2000, 1, 1);
    Y2KChecker.Check();
}
  1. In Solution Explorer, expand your unit test project’s References.
    • If you are working in Visual Basic, you must select Show All Files in the Solution Explorer toolbar, in order to see the References list.
  2. Select the assembly that contains the classes definitions for which you want to create shims. For example, if you want to shim DateTime, select System.dll
  3. On the shortcut menu, choose Add Fakes Assembly.
When using shim types in a unit test framework, you must wrap the test code in a ShimsContext to control the lifetime of your shims. If we didn’t require this, your shims would last until the AppDomain shut down. The easiest way to create a ShimsContext is by using the static Create() method as shown in the following code:
//unit test code
[Test]
public void Y2kCheckerTest() {
  using(ShimsContext.Create()) {
    ...
  } // clear all shims
}
It is critical to properly dispose each shim context. As a rule of thumb, always call the ShimsContext.Create inside of a using statement to ensure proper clearing of the registered shims. For example, you might register a shim for a test method that replaces the DateTime.Now method with a delegate that always returns the first of January 2000. If you forget to clear the registered shim in the test method, the rest of the test run would always return the first of January 2000 as the DateTime.Now value. This might be suprising and confusing.
In your test code, insert a detour for the method you want to fake. For example:
[TestClass]
public class TestClass1
{ 
        [TestMethod]
        public void TestCurrentYear()
        {
            int fixedYear = 2000;

            using (ShimsContext.Create())
            {
              // Arrange:
                // Detour DateTime.Now to return a fixed date:
                System.Fakes.ShimDateTime.NowGet = 
                () =>
                { return new DateTime(fixedYear, 1, 1); };

                // Instantiate the component under test:
                var componentUnderTest = new MyComponent();

              // Act:
                int year = componentUnderTest.GetTheCurrentYear();

              // Assert: 
                // This will always be true if the component is working:
                Assert.AreEqual(fixedYear, year);
            }
        }
}
Shim class names are made up by prefixing Fakes.Shim to the original type name.
Shims work by inserting detours into the code of the application under test. Wherever a call to the original method occurs, the Fakes system performs a detour, so that instead of calling the real method, your shim code is called.
Notice that detours are created and deleted at run time. You must always create a detour within the life of a ShimsContext. When it is disposed, any shims you created while it was active are removed. The best way to do this is inside a using statement.
You might see a build error stating that the Fakes namespace does not exist. This error sometimes appears when there are other compilation errors. Fix the other errors and it will vanish.
Shim types allow you to replace any .NET method, including static methods or non-virtual methods, with your own delegates.
The properties to attach shims to static methods are placed in a shim type. Each property has only a setter that can be used to attach a delegate to the target method. For example, given a class MyClass with a static method MyMethod:
//code under test
public static class MyClass {
    public static int MyMethod() {
        ...
    }
}
We can attach a shim to MyMethod that always returns 5:
// unit test code
ShimMyClass.MyMethod = () =>5;
Similarly to static methods, instance methods can be shimmed for all instances. The properties to attach those shims are placed in a nested type named AllInstances to avoid confusion. For example, given a class MyClass with an instance method MyMethod:
// code under test
public class MyClass {
    public int MyMethod() {
        ...
    }
}
You can attach a shim to MyMethod that always returns 5, regardless of the instance:
// unit test code
ShimMyClass.AllInstances.MyMethod = () => 5;
The generated type structure of ShimMyClass looks like the following code:
// Fakes generated code
public class ShimMyClass : ShimBase<MyClass> {
    public static class AllInstances {
        public static Func<MyClass, int>MyMethod {
            set {
                ...
            }
        }
    }
}
Notice that Fakes passes the runtime instance as the first argument of the delegate in this case.
Instance methods can also be shimmed by different delegates, based on the receiver of the call. This enables the same instance method to have different behaviors per instance of the type. The properties to set up those shims are instance methods of the shim type itself. Each instantiated shim type is also associated with a raw instance of a shimmed type.
For example, given a class MyClass with an instance method MyMethod:
// code under test
public class MyClass {
    public int MyMethod() {
        ...
    }
}
We can set up two shim types of MyMethod such that the first one always returns 5 and the second always returns 10:
// unit test code
var myClass1 = new ShimMyClass()
{
    MyMethod = () => 5
};
var myClass2 = new ShimMyClass { MyMethod = () => 10 };
The generated type structure of ShimMyClass looks like the following code:
// Fakes generated code
public class ShimMyClass : ShimBase<MyClass> {
    public Func<int> MyMethod {
        set {
            ...
        }
    }
    public MyClass Instance {
        get {
            ...
        }
    }
}
The actual shimmed type instance can be accessed through the Instance property:
// unit test code
var shim = new ShimMyClass();
var instance = shim.Instance;
The shim type also has an implicit conversion to the shimmed type, so you can usually simply use the shim type as is:
// unit test code
var shim = new ShimMyClass();
MyClass instance = shim; // implicit cast retrieves the runtime
                         // instance
Constructors can also be shimmed in order to attach shim types to future objects. Each constructor is exposed as a static method Constructor in the shim type. For example, given a class MyClass with a constructor taking an integer:
// code under test
public class MyClass {
    public MyClass(int value) {
        this.Value = value;
    }
    ...
}
We set up the shim type of the constructor so that every future instance returns -5 when the Value getter is invoked, regardless of the value in the constructor:
// unit test code
ShimMyClass.ConstructorInt32 = (@this, value) => {
    var shim = new ShimMyClass(@this) {
        ValueGet = () => -5
    };
};
Note that each shim type exposes two constructors. The default constructor should be used when a fresh instance is needed, while the constructor taking a shimmed instance as argument should be used in constructor shims only:
// unit test code
public ShimMyClass() { }
public ShimMyClass(MyClass instance) : base(instance) { }
The generated type structure of ShimMyClass resembles the followoing code:
// Fakes generated code
public class ShimMyClass : ShimBase<MyClass>
{
    public static Action<MyClass, int> ConstructorInt32 {
        set {
            ...
        }
    }

    public ShimMyClass() { }
    public ShimMyClass(MyClass instance) : base(instance) { }
    ...
}
The shim properties of base members can be accessed by creating a shim for the base type and passing the child instance as a parameter to the constructor of the base shim class.
For example, given a class MyBase with an instance method MyMethod and a subtype MyChild:
public abstract class MyBase {
    public int MyMethod() {
        ...
    }
}

public class MyChild : MyBase {
}
We can set up a shim of MyBase by creating a new ShimMyBase shim:
// unit test code
var child = new ShimMyChild();
new ShimMyBase(child) { MyMethod = () => 5 };
Note that the child shim type is implicitly converted to the child instance when passed as a parameter to the base shim constructor.
The generated type structure of ShimMyChild and ShimMyBase resembles the following code:
// Fakes generated code
public class ShimMyChild : ShimBase<MyChild> {
    public ShimMyChild() { }
    public ShimMyChild(Child child)
        : base(child) { }
}
public class ShimMyBase : ShimBase<MyBase> {
    public ShimMyBase(Base target) { }
    public Func<int> MyMethod
    { set { ... } }
}
Shim types expose a static method StaticConstructor to shim the static constructor of a type. Since static constructors are executed once only, you need to ensure that the shim is configured before any member of the type is accessed.
Finalizers are not supported in Fakes.
The Fakes code generator will create shim properties for private methods that only have visible types in the signature, i.e. parameter types and return type visible.
When a shimmed type implements an interface, the code generator emits a method that allows it to bind all the members from that interface at once.
For example, given a class MyClass that implements IEnumerable<int>:
public class MyClass : IEnumerable<int> {
    public IEnumerator<int> GetEnumerator() {
        ...
    }
    ...
}
We can shim the implementations of IEnumerable<int> in MyClass by calling the Bind method:
// unit test code
var shimMyClass = new ShimMyClass();
shimMyClass.Bind(new List<int> { 1, 2, 3 });
The generated type structure of ShimMyClass resembles the following code:
// Fakes generated code
public class ShimMyClass : ShimBase<MyClass> {
    public ShimMyClass Bind(IEnumerable<int> target) {
        ...
    }
}
Each generated shim type holds an instance of the IShimBehavior interface, through the ShimBase<T>.InstanceBehavior property. The behavior is used whenever a client calls an instance member that was not explicitly shimmed.
If the behavior has not been explicitly set, it will use the instance returned by the static ShimsBehaviors.Current property. By default, this property returns a behavior that throws a NotImplementedException exception.
This behavior can be changed at any time by setting the InstanceBehavior property on any shim instance. For example, the following snippet changes the shim to a behavior that does nothing or returns the default value of the return type—that is, default(T):
// unit test code
var shim = new ShimMyClass();
//return default(T) or do nothing
shim.InstanceBehavior = ShimsBehaviors.DefaultValue;
The behavior can also be changed globally for all shimmed instances for which the InstanceBehavior property was not explicitly set by setting the staticShimsBehaviors.Current property:
// unit test code
// change default shim for all shim instances
// where the behavior has not been set
ShimsBehaviors.Current = 
    ShimsBehaviors.DefaultValue;
It is possible to attach a behavior to all the members, including static methods, of a particular type by assigning the ShimsBehaviors.NotImplemented behavior to the static property Behavior of the corresponding shim type:
// unit test code
// assigning the not implemented behavior
ShimMyClass.Behavior = ShimsBehaviors.NotImplemented;
// shorthand
ShimMyClass.BehaveAsNotImplemented();
Shim types apply to all threads in the AppDomain and don’t have thread affinity. This is an important fact if you plan to use a test runner that support concurrency: tests involving shim types cannot run concurrently. This property is not enfored by the Fakes runtime.
Imagine that we wanted to actually write the text to the file system after validating the file name passed to the method. In that case, we would want to call the original method in the middle of the shim method.
The first approach to solve this problem is to wrap a call to the original method using a delegate and ShimsContext.ExecuteWithoutShims() as in the following code:
// unit test code
ShimFile.WriteAllTextStringString = (fileName, content) => {
  ShimsContext.ExecuteWithoutShims(() => {

      Console.WriteLine("enter");
      File.WriteAllText(fileName, content);
      Console.WriteLine("leave");
  });
};
Another approach is to set the shim to null, call the original method and restore the shim.
// unit test code
ShimsDelegates.Action<string, string> shim = null;
shim = (fileName, content) => {
  try {
    Console.WriteLine("enter”);
    // remove shim in order to call original method
    ShimFile.WriteAllTextStringString = null;
    File.WriteAllText(fileName, content);
  }
  finally
  {
    // restore shim
    ShimFile.WriteAllTextStringString = shim;
    Console.WriteLine("leave");
  }
};
// initialize the shim
ShimFile.WriteAllTextStringString = shim;
Shims cannot be used on all types from the .NET base class library mscorlib and System.


http://msdn.microsoft.com/en-us/library/hh549176.aspx