1

When I try to update the task properties of the workflow from my webpart, I get the following exception:

Microsoft.SharePoint.SPException: Task Updates are not allowed via unstrusted code
at Microsoft.SharePoint.SPListItem.PrepareItemForUpdate(Guid newGuidOnAdd,Boolean bMigration, Boolean& bAdd, Boolean& bPublish,Object& objAttachmentNames, Object& objAttachmentContents,Int32& parentFolderId) 
at Microsoft.SharePoint.SPListItem.UpdateInternal(Boolean bSystem, BooleanbPreserveItemVersion, Guid newGuidOnAdd, Boolean bMigration, Boolean
bPublish, Boolean bNoVersion, Boolean bCheckOut, Boolean bCheckin,Boolean suppressAfterEvents) 
at Microsoft.SharePoint.SPListItem.Update() 
at Microsoft.SharePoint.Workflow.SPWorkflowTask.AlterTask(SPListItem task,Hashtable htData, Boolean fSynchronous)

Sample code used to update the task is:

Hashtable props = new Hashtable();
props.Add(SPBuiltInFieldId.AssignedTo, finalAssignedTo);
props.Add(SPBuiltInFieldId.Completed, "0");
props.Add(SPBuiltInFieldId.TaskStatus, "In Progress");
props.Add(SPBuiltInFieldId.Priority, "(2) Normal");
props.Add(SPBuiltInFieldId.TaskType, "0");
task.Web.AllowUnsafeUpdates = true;
bool outcome = SPWorkflowTask.AlterTask(task, props, true);

The web part is deployed under the bin directory. We have set custom CAS policy for this web part. Following is my CAS policy.

<CodeAccessSecurity>
    <PolicyItem>
      <PermissionSet class="NamedPermissionSet" version="1" Name="MyPermission" Description="Permission set for my solution">
        <IPermission class="System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Level="Medium"    />
        <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
        <IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
        <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="AllFlags" />
        <IPermission class="Microsoft.SharePoint.Security.WebPartPermission, Microsoft.SharePoint.Security, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" version="1" Connections="true"    />
        <IPermission class="Microsoft.SharePoint.Security.SharePointPermission, Microsoft.SharePoint.Security, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"    version="1"    ObjectModel="true" UnsafeSaveOnGet="true" Impersonate="true"/>
        <IPermission class="System.Net.WebPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true">
          <ConnectAccess>
            <URI uri="$OriginHost$"/>
            <URI uri="http://.*\.....\.com/.*"/>
          </ConnectAccess>
        </IPermission>
      </PermissionSet>
      <Assemblies>
        <Assembly Name="MyOffice" Version="1.0.0.0" PublicKeyBlob="0024000004800000940000000602000000240000525341310004000001000100df0e85cb8c660241cd3225eb653a590b91303ddbd37f8f1e661d2dffb840a258b899d6bacbbc55d03768d5ea0260ee4c8341fd447d7200abdb74b837733c3f756833e169cae803aef808530dd3ddad953a49492faee3eeba6f0dba66b0d66f1f9ca5266c69dcb799ed364db5e9e6ebcd4e81fb27365de962cbe6e7e7fba300dc"/>
      </Assemblies>
    </PolicyItem>
  </CodeAccessSecurity>

Please advise.

2 Answers2

0

You need to deploy your workflow assemblies to the GAC.

this the Microsoft best practice. see the Ms patterns and pratices.

also you need to allow partially trusted callers sharepoint web part: see step 3 here:

msdn.microsoft.com/en-us/library/ms452873.aspx

Chris Jones
  • 2,630
  • 2
  • 21
  • 34
0

Partial Public Class Request1 Inherits WebPart

' Uncomment the following SecurityPermission attribute only when doing Performance Profiling on a farm solution
' using the Instrumentation method, and then remove the SecurityPermission attribute when the code is ready
' for production. Because the SecurityPermission attribute bypasses the security check for callers of
' your constructor, it's not recommended for production purposes.
' <System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Assert, UnmanagedCode := True)> _
Public Sub New()
End Sub

Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
    MyBase.OnInit(e)
    InitializeControl()
End Sub

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim IntItemID As Integer
    If Not Page.IsPostBack Then

        Dim siteId As Guid = SPContext.Current.Site.ID
        Dim webId As Guid = SPContext.Current.Web.ID

        Using objSpSite As New SPSite(siteId)
            Using objSpWeb As SPWeb = objSpSite.OpenWeb(webId)
                txtCurrentUserName.Text = objSpWeb.CurrentUser.Name

                If Not Page.Request.QueryString("ItemID") Is Nothing And Page.Request.QueryString("ItemID") <> "" Then
                    IntItemID = CInt(Page.Request.QueryString.Item("ItemID").ToString)
                    Panel1.Visible = False

                    txtID.Text = IntItemID.ToString
                    Dim objList As SPList = objSpWeb.Lists("RequestList")
                    Dim objListItem As SPListItem = objList.Items.GetItemById(IntItemID)
                    dtPermission.SelectedDate = objListItem("PermissionDate")
                    dtTimeFrom.SelectedDate = objListItem("PermissionFromTime")
                    dtTimeTo.SelectedDate = objListItem("PermissionToTime")
                    cmbType.SelectedValue = objListItem("PermissionType")
                    txtManager.Text = objListItem("Manager1Name")
                    txtManagerUserName.Text = objListItem("Manager1UserName")
                    txtCount.Text = objListItem("PermissionCount")

                    Dim objCrUser As SPFieldUser
                    objCrUser = objListItem.Fields.GetFieldByInternalName("Author")
                    Dim objCrUserValue As SPFieldUserValue
                    objCrUserValue = objCrUser.GetFieldValue(objListItem("Author").ToString())
                    txtCreatedBy.Text = objCrUserValue.User.Name
                    dtCreated.SelectedDate = objListItem("Created")

                    Dim objWFTask As SPWorkflowTask = objListItem.Tasks(0)

                    If objWFTask Is Nothing Then

                        If objWFTask.DoesUserHavePermissions(SPBasePermissions.ApproveItems) = False Then
                            Panel2.Visible = False
                        End If

                    End If


                Else
                    IntItemID = 0
                    txtID.Text = "New"
                    dtCreated.SelectedDate = Today
                    txtCreatedBy.Text = objSpWeb.CurrentUser.Name
                    Dim objServiceContext As SPServiceContext = SPServiceContext.GetContext(objSpSite)
                    Dim objUserProfileManager As New UserProfileManager(objServiceContext)

                    Dim objUserProfile As UserProfile
                    Dim strUserAccount As String
                    strUserAccount = objSpWeb.CurrentUser.LoginName.Replace("i:0#.w|", "")
                    If objUserProfileManager.UserExists(strUserAccount) Then
                        objUserProfile = objUserProfileManager.GetUserProfile(strUserAccount)
                        Try
                            txtManager.Text = objUserProfile.GetManager.DisplayName
                            txtManagerUserName.Text = objUserProfile.GetManager.AccountName
                        Catch ex As Exception
                            txtManager.Text = ex.Message
                        End Try

                    End If


                    Panel2.Visible = False

                End If

            End Using
        End Using

    End If

End Sub

Protected Sub cmdSubmit_Click(sender As Object, e As EventArgs) Handles cmdSubmit.Click
    Dim siteId As Guid = SPContext.Current.Site.ID
    Dim webId As Guid = SPContext.Current.Web.ID

    Using objSpSite As New SPSite(siteId)
        Using objSpWeb As SPWeb = objSpSite.OpenWeb(webId)
            objSpWeb.AllowUnsafeUpdates = True
            Dim list As SPList = objSpWeb.Lists("RequestList")
            Dim item As SPListItem = list.Items.Add()
            item("PermissionDate") = dtPermission.SelectedDate
            item("PermissionFromTime") = dtTimeFrom.SelectedDate
            item("PermissionToTime") = dtTimeTo.SelectedDate
            item("PermissionType") = cmbType.SelectedValue
            item("Manager1Name") = txtManager.Text
            item("Manager1UserName") = txtManagerUserName.Text
            item("PermissionCount") = CInt("0" & txtCount.Text.ToString)

            item.Update()
            list.Update()
            objSpWeb.AllowUnsafeUpdates = False
        End Using
    End Using

End Sub

Protected Sub cmdApprove_Click(sender As Object, e As EventArgs) Handles cmdApprove.Click
    Dim siteId As Guid = SPContext.Current.Site.ID
    Dim webId As Guid = SPContext.Current.Web.ID
    Using objSpSite As New SPSite(siteId)
        Using objSpWeb As SPWeb = objSpSite.OpenWeb(webId)
            Dim objList As SPList = objSpWeb.Lists("RequestList")
            Dim objListItem As SPListItem = objList.Items.GetItemById(CInt(txtID.Text))

            Dim objWFTask As SPWorkflowTask = objListItem.Tasks(0)

            If objWFTask Is Nothing Then
                ' no matching task
                Return
            End If

            ' alter the taska
            Dim taskHash As New Hashtable()

            taskHash("Status") = "Complete"
            taskHash("PercentComplete") = 1.0F
            taskHash("TaskStatus") = "Approved"
            'taskHash("SPBuiltInFieldId.TaskStatus") = SPResource.GetString(New CultureInfo(CInt(task.Web.Language), False), Strings.WorkflowStatusCompleted, New Object(-1))

            taskHash("TaskOutcome") = "Approved"
            taskHash("Outcome") = "Approved"
            taskHash("SPBuiltInFieldId.WorkflowOutcome") = "Approved"
            taskHash("Approved") = "true"
            taskHash("Comments") = "Approved By Manager"


            objSpWeb.AllowUnsafeUpdates = True
            SPWorkflowTask.AlterTask(TryCast(objWFTask, SPListItem), taskHash, False)
            objSpWeb.AllowUnsafeUpdates = False

        End Using
    End Using



End Sub

Protected Sub cmdReject_Click(sender As Object, e As EventArgs) Handles cmdReject.Click
    Dim siteId As Guid = SPContext.Current.Site.ID
    Dim webId As Guid = SPContext.Current.Web.ID
    Using objSpSite As New SPSite(siteId)
        Using objSpWeb As SPWeb = objSpSite.OpenWeb(webId)
            Dim objList As SPList = objSpWeb.Lists("RequestList")
            Dim objListItem As SPListItem = objList.Items.GetItemById(CInt(txtID.Text))

            Dim objWFTask As SPWorkflowTask = objListItem.Tasks(0)

            If objWFTask Is Nothing Then
                ' no matching task
                Return
            End If

            ' alter the taska
            Dim taskHash As New Hashtable()

            taskHash("Status") = "Complete"
            taskHash("PercentComplete") = 1.0F
            taskHash("TaskStatus") = "Rejected"
            'taskHash("SPBuiltInFieldId.TaskStatus") = SPResource.GetString(New CultureInfo(CInt(task.Web.Language), False), Strings.WorkflowStatusCompleted, New Object(-1))

            taskHash("TaskOutcome") = "Rejected"
            taskHash("Outcome") = "Rejected"
            taskHash("SPBuiltInFieldId.WorkflowOutcome") = "Rejected"
            taskHash("Rejected") = "true"
            taskHash("Comments") = "Rejected By Manager"

            objSpWeb.AllowUnsafeUpdates = True
            SPWorkflowTask.AlterTask(TryCast(objWFTask, SPListItem), taskHash, False)
            objSpWeb.AllowUnsafeUpdates = False

        End Using
    End Using
End Sub

End Class