Wednesday, March 28, 2012

Emailing Documents as Attachments Workflow Activity for Sharepoint 2010

One of the most obvious use cases which is lacking from SharePoint is the ability to email documents as attachments directly from SharePoint, instead of just a hyperlink pointing to the selected document.
Currently, our SharePoint users requested to implement sending documents to external partners or suppliers through workflow approval. In order to enforce the security policies and protect IP, the documents will be converted to PDF with designed watermark using third party tool. The documents will be submitted to workflow approval process and the actions will be recorded for auditing purpose.
Now, the question is how we could incorporate the email documents as attachments into the workflow. The best option is to develop a workflow activity for reuse. Before jumping directly to the development, we found some useful commercial third party tools and free CodePlex functions we could use. 

Here is the summary for you to select if you do not want to develop yourself.

1. HarePointWorkflow Extension for SharePoint 2010 - provides over 180 new 'ready-to-use' activities for SharePoint workflow development. The product is fully supported by all Microsoft workflow development tools and there is no need to migrate and adapt current workflows to a new development environment, or to master and deploy new development tools. You can benefit from the power of the product in SharePoint Designer 2010, Microsoft Visual Studio 2010, and in Microsoft Visio 2010.

Here is the summary of the HarePoint workflow activity for email. 



2. Virto SharePoint 2010 Workflow Activities Kit – no-code set of SharePoint activities for creating custom Workflow using SharePoint Workflow Designer. Virto Workflow Kit that can be used as an add-on for MS SharePoint 2010 includes extended activities for sending e-mails and SMS as well as messaging to Twitter, Jabber and Miranda. 

3. CodePlex SP Designer Activity - Send Email withAttachment - The new version adds support for Folders and Document Sets. If a user selects a folder or document set to run the workflow on this activity will get all items from the folder / document set and add them as attachments to the email.

The advantages of commercial third party tools are:
o  No-code and Ready-to-use Activities
o  Easy Deployment (just add them into your SharePoint Designer)
o  Enhanced Capabilities for your Custom Workflow Creation
o  Vendor support
The advantages of CodePlex tools are:
o  Free
o  Easy to modify since it comes with source code
o  User community support

Sometime, we found third party or CodePlex tools are working well on single SharePoint server. Even some big vendor products are not working consistently on three tier architecture with separate web front servers and application servers. As a result, please carefully evaluate the third party tools.

If you need to add email attachments directly to the list, you could check the following tools
 As always, you should implement email validation. The one in CodePlex should be very helpful.

We are in the process to select and implement this function and will share our experience when it’s done. If you have any experience on any of these tools, please let me know your input.

Wednesday, March 7, 2012

How to resolve issue to open Document Library as Compressed (zipped) Folder Allitems.zip?

We have users reported the following issue in production last night. Users try to open one Document library http://servername/sites/department/subsite/Products  and get the following dialog with the message.


Do you want to open or save this file?
  • Name: Allitems.zip
  • Type: Compressed (zipped) Folder
  • From: SharePoint Webapp name 

If you click "open", you're redirected to a blank page in SharePoint and users could not access the documents inside the library.

When I open the AllItem.aspx through SharePoint designer, it display the unreadable content. This indicates that this file has been corrupted. 


There are several ways you could fix it quickly. Here are two simple ways for your references.
  1.  Get backup for the site and copy the AllItem.aspx to the existing site. You may require DBA to get the backup.
  2. Create a new view for the library and set as the default view. Delete the previous default view AllItem.aspx. Rename the new view as AllItems.aspx.
Option one is very straight forward and no future explanation. I'll explain the option #2 here in details.

Since you are not able to access the library, the URL to the library is the default view for the library. You could access the list edit view through the following URL

 
 
Please note the last parameter is the list GUID that you could get easily through SharePoint Designer when you click the list. See the following screen shot.
 
 
 
Now, you could create the new view and set as default. You should be access the library now!

In order to keep the original URL to access the library, you could delete the previous default view AllItems.aspx. Then rename the new view to previous AllItem.aspx.


Now users could access the library using the same URL now http://servername/sites/department/subsite/Products.

 
 




Tuesday, March 6, 2012

Best practice for SharePoint developers to create new objects

When you create SharePoint objects, you may need to clean up the older version of the object before creating it. This is a good practice to avoid multiple instances or wrong content associated with the objects. Here are two examples.

The first is SharePoint timer job example. Before creating the timer job, the best practice is to delete the older version of the job definition. This might save you lots of time to debug since the new timer job may not even be reflected after the deployment due to the timer job cache. Here is the code example.

//Good Practice to delete the older version of Job if it exists
foreach (SPJobDefinition job in webApp.JobDefinitions)
{
      if (job.Name.ToLower() == myJobName.ToLower())
      {
           job.Delete();
      }
}

//Install the job definition
SyncListsJob tempJob = new SyncListsJob (myJobName,webApp);
 
  
//If you want to run it every hour, use SPHourlySchedule class to configure.
//This one will run between 0 to 5 minutes of every hour
  
SPHourlySchedule schedule = new SPHourlySchedule();
schedule.BeginMinute = 0;
schedule.EndMinute = 5;
tempJob.Schedule = schedule;
tempJob.Update();

 
The second is SharePoint role assignment. Before you assign the role, the best practice is to remove all the existing roles so we know exactly what role will be assigned. Here is the example.


SPRoleAssignment roleAssignment;
//update existing role assignment
roleAssignment = rootWeb.RoleAssignments.GetAssignmentByPrincipal(
                (SPPrincipal)rootWeb.SiteGroups[siteGroupOwnerName]);

// Good practice to delete older role assignment before assigning new one
roleAssignment.RoleDefinitionBindings.RemoveAll();
      roleAssignment.RoleDefinitionBindings.Add(rootWeb.RoleDefinitions[permissionLevelName]);
roleAssignment.Update();


The third is web part example. Before add user control to the web part, the best practice is to clear the controls first. Code example is

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
 
            // Best practice to clear the controls first 
Controls.Clear();
            myLabel = new Label();
            myLabel.Text = "This is the best practice";
            Controls.Add(myLabel);
        }

 We should apply the same best practice when creating many other SharePoint objects such as Policy. We are encourage new developers in the team to adopt this best practice.

Wednesday, February 15, 2012

Best practice to impersonate users for SharePoint API calls

We have a requirement to develop a event receiver to copy list items into another list. During the design, I’ve asked developer not only copy the list items, but also keep the created by and modified by same as source list so that the audit history will reflect the active users.

The way to implement is to impersonate the call. Here is simple example.

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Impersonate
            string siteStr = "http://sbx08/sites/Harry/";

            using (SPSite site = new SPSite(siteStr))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    // Impersonate to user “an/harryc”
                    SPUserToken utoken = web.AllUsers["na/harryc"].UserToken;

                // Open site as that user
                    using (SPSite newSite = new SPSite(siteStr, utoken))
                    {
                        using (SPWeb newWeb = newSite.OpenWeb())
                        {
                            Console.WriteLine(newWeb.CurrentUser.ToString());

                            // Impersonate code to interact with SharePoint
                        }
                    }

                }
            }
        }
    }
}


If users do not have the permission on the destination list, we have to use run with elevated privileges.

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite site = new SPSite(SPContext.Current.Site.ID))
    {
        using (SPWeb elevatedWeb = site.OpenWeb(webId))
        {
            //Your code here
        }
    }
});


All these two are very common and I just want to keep the sample in my blog to train my new developers.

Thursday, February 9, 2012

Is there any way we could do only block the Web services calls for external programs but open to WebDav and SharePoint Designer on site level?

We have a production site with out of office calendar list. One designer workflow will send email notification for out of office approval if any calendar item created or modified. Today, all calendar items were updated at same time that trigger old pending workflows been send out to many people!

We looked at the logs and found all those entries are updated by one user name. The log also shows the is should caused by the web service call.

02/09/2012 11:46:29.07 w3wp.exe (0x3A90)                       0x111C  SharePoint Foundation                 Logging Correlation Data                      xmnv     Medium               Name=Request (POST:http://serverURL:80/ourSIte/_vti_bin/lists.asmx)                2ae0784f-bd97-4098-9e15-d147a8b11ed4

Since any SharePoint users who have the permission could use web service calls and hit SharePoint server programmatically, we are concerned of DOA (Deny Of Access) and performance. We would like to have the capability to disable the SharePoint web service on the site level for external users besides SharePoint internal calls.

I did some search and found two possible ways that might block the web services on WebApp level. However, one option will block any of the web services,  SOAP, WebDav, SharePoint Designer. Another option will require Front server and TMG.

Is there any way we could do only block the Web services calls for external programs but open to WebDav and SharePoint Designer on site level?

I tried to access the admin web service (http://servername/SIteURL/_vti_admin/admin.asmx) and got the following error.  Is there anything we could do similar to other web services through global security group access?


Thanks.

Wednesday, February 8, 2012

LINQ could not access SharePoint 2010 managed metadate list columns

LINQ is a very simple and powerful way of querying data in the .Net programming language as we mentioned before. It allows the .Net language to query data natively against strongly typed classes. Yes against class with objects through DataContext generated by SPMetal.exe tool. SharePoint will convert the LINQ to CAML during the runtime. As a result, LINQ is an easy way comparing to older CAML to work with list data. Here is example to use LINQ to SharePoint 2010 with tricks and limitations.

1. Create a list named “City” with three columns “City”, “State”, and MMD that is managed meta column on site http://sbx08/sites/Harry/.

2. Create several entries and file in MMD columns as in the screen shot


3. Use SPMetal.exe located in ..\14\BIN to generate DataContext so you could use the objects in LINQ
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN>spmetal /web:http://sbx08/sites/Harry/ /namespace:HarrySite /code:HarrySite.cs /language:csharp /useremoteapieapi

spmetal /web:http://sbx08/sites/Harry/ /namespace:HarrySite /code:HarrySite.cs /language:csharp /useremoteapieapi

4. Follow the procedure we mentioned before to add DataContext class. In the DataContext class HarrySite.cs, you will find the attributes “City” and State” for City list. However, there is no MMD attribute generated for this managed meta column. See the following  SPMetal generated code for City list.

[Microsoft.SharePoint.Linq.ContentTypeAttribute(Name="Item", Id="0x01", List="City")]
       public partial class CityItem : Item {
             
              private string _state;
             
              private string _city;
             
              #region Extensibility Method Definitions
              partial void OnLoaded();
              partial void OnValidate();
              partial void OnCreated();
              #endregion
             
              public CityItem() {
                     this.OnCreated();
              }
             
              [Microsoft.SharePoint.Linq.ColumnAttribute(Name="State", Storage="_state", FieldType="Text")]
              public string State {
                     get {
                           return this._state;
                     }
                     set {
                           if ((value != this._state)) {
                                  this.OnPropertyChanging("State", this._state);
                                  this._state = value;
                                  this.OnPropertyChanged("State");
                           }
                     }
              }
             
              [Microsoft.SharePoint.Linq.ColumnAttribute(Name="City", Storage="_city", FieldType="Text")]
              public string City {
                     get {
                           return this._city;
                     }
                     set {
                           if ((value != this._city)) {
                                  this.OnPropertyChanging("City", this._city);
                                  this._city = value;
                                  this.OnPropertyChanged("City");
                           }
                     }
              }
       }

If you try to use the column MMD from DataContext, it will NOT find the reference. This seems to be a bug and it is similar to the issue REST web service could not retrieve data form managed metadata reported before.

We will work with Microsoft and keep you posted.