2013년 2월 3일 일요일

vsto outlook ItemAdd event on a public folder on Exchange

vsto outlook ItemAdd event on a public folder on Exchange



Continuous googling did its job. I found how to resolve the issue. It appears I am not the only one who experience it.
I added the reference to Items collection of the folder I want to track to the global scope:
internal static class stor
{
    public static Outlook.Items i;
}

public partial class ThisAddIn
{
    internal static Outlook.Folder posts_folder = null;

    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        // the code for finding a posts_folder is omitted

        stor.i = posts_folder.Items;
        stor.i.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(Posts_Add);
    }

    static void Posts_Add(object Item)
    {
        System.Windows.Forms.MessageBox.Show("New item");
    }
{
Now it works as expected. Alhough I do not understand all the details they say it is a garbage collection issue. My event handler eventually was thrown into the garbage. The reference to the Items collection on the global scope prevents this from happening.
http://social.msdn.microsoft.com/Forums/en-AU/vsto/thread/28d91a1a-34ec-476d-8f49-0d26aff8a376


http://stackoverflow.com/questions/8562214/itemadd-event-on-a-public-folder-on-exchange

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