Benutzer:MovGP0/Nintex/Custom Activity

aus Wikipedia, der freien Enzyklopädie
Zur Navigation springen Zur Suche springen
   MovGP0        Über mich        Hilfen        Artikel        Weblinks        Literatur        Zitate        Notizen        Programmierung        MSCert        Physik      


Custom Activity

[Bearbeiten | Quelltext bearbeiten]
using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.WorkflowActions;
using Nintex.Workflow;
using Nintex.Workflow.Activities;
using Nintex.Workflow.Activities.Adapters;
using Nintex.Workflow.Diagnostics;
using System;
using System.Workflow.ComponentModel;

namespace FWI.SharePoint.CFLEX.Nintex.ActivityLibrary
{
    public class CopyItemActivity : ProgressTrackingActivity
    {
        #region Properties
        public static DependencyProperty __ContextProperty = DependencyProperty.Register("__Context", typeof(WorkflowContext), typeof(CopyItemActivity));
        public WorkflowContext Context
        {
            get { return (WorkflowContext)GetValue(__ContextProperty); }
            set { base.SetValue(__ContextProperty, value); }
        }

        public static DependencyProperty __ListItemProperty = DependencyProperty.Register("__ListItem", typeof(SPItemKey), typeof(CopyItemActivity));
        public SPItemKey ListItem
        {
            get { return (SPItemKey)GetValue(__ListItemProperty); }
            set { SetValue(__ListItemProperty, value); }
        }

        public static DependencyProperty __ListIdProperty = DependencyProperty.Register("__ListId", typeof(string), typeof(CopyItemActivity));
        public string SourceListId
        {
            get { return (string)GetValue(__ListIdProperty); }
            set { SetValue(__ListIdProperty, value); }
        }

        public static DependencyProperty TargetListNameProperty = DependencyProperty.Register("TargetListName", typeof(string), typeof(CopyItemActivity));
        public string TargetListName
        {
            get { return (string)GetValue(TargetListNameProperty); }
            set { SetValue(TargetListNameProperty, value); }
        }

        public static DependencyProperty CaptureErrorsProperty = DependencyProperty.Register("CaptureErrors", typeof(bool), typeof(CopyItemActivity));
        public bool CaptureErrors
        {
            set { base.SetValue(CaptureErrorsProperty, value); }
            get { return (bool)base.GetValue(CaptureErrorsProperty); }
        }

        public static DependencyProperty ErrorOccurredOutputProperty = DependencyProperty.Register("ErrorOccurredOutput", typeof(bool), typeof(CopyItemActivity));
        public bool ErrorOccurredOutput
        {
          set { base.SetValue(ErrorOccurredOutputProperty, value); }
          get { return (bool)base.GetValue(ErrorOccurredOutputProperty); }
        }

        public static DependencyProperty ErrorMessageOutputProperty = DependencyProperty.Register("ErrorMessageOutput", typeof(string), typeof(CopyItemActivity));
        public string ErrorMessageOutput
        {
            set { base.SetValue(ErrorMessageOutputProperty, value); }
            get { return (string)base.GetValue(ErrorMessageOutputProperty); }
        }

        #endregion

        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            var sourceListGuid = new Guid(SourceListId);
            var workflowContext = NWWorkflowContext.GetContext(Context, sourceListGuid, ListItem.Id, WorkflowInstanceId, this);
            EnsureActivityIsAllwowed();

            LogProgressStart(workflowContext);

            var sourceList = Context.Web.Lists[sourceListGuid];
            var targetList = Context.Web.Lists[TargetListName];

            var sourceItem = sourceList.GetItemById(ListItem.Id);
            var targetItem = targetList.AddItem();

            CopyAllFieldsExceptAttachments(sourceItem, targetItem);
            CopyAttachments(sourceItem, targetItem);

            targetItem.Update();
            targetList.Update();

            LogProgressEnd(workflowContext, executionContext);
            return ActivityExecutionStatus.Closed;
        }

        private void EnsureActivityIsAllwowed()
        {
            ActivityActivationReference.IsAllowed(this, Context.Web);
        }

        private void CopyAllFieldsExceptAttachments(SPListItem sourceItem, SPListItem targetItem)
        {
            foreach (SPField field in sourceItem.Fields)
            {
                if (!FieldCanBeCopied(sourceItem, field)) continue;
                try
                {
                    targetItem[field.InternalName] = sourceItem[field.InternalName];
                }
                catch (ArgumentException ae)
                {
                    if (CaptureErrors)
                    {
                        ErrorOccurredOutput = true;
                        ErrorMessageOutput += ae.Message;
                    }
                }
            }
        }

        private static void CopyAttachments(SPListItem sourceItem, SPListItem targetItem)
        {
            foreach (string fileName in sourceItem.Attachments)
            {
                SPFile file = sourceItem.ParentList.ParentWeb.GetFile(sourceItem.Attachments.UrlPrefix + fileName);
                byte[] data = file.OpenBinary();
                targetItem.Attachments.Add(fileName, data);
            }
        }

        private static bool FieldCanBeCopied(SPListItem sourceItem, SPField field)
        {
            return !field.ReadOnlyField
                   && field.InternalName != "Attachments"
                   && sourceItem[field.InternalName] != null;
        }

        protected override ActivityExecutionStatus HandleFault(ActivityExecutionContext executionContext, Exception exception)
        {
            ActivityErrorHandler.HandleFault(executionContext, exception, WorkflowInstanceId, "Error while copying item.", ListItem.Id, SourceListId, Context);
            return base.HandleFault(executionContext, exception);
        }

    }
}

File is in COMPANY.SharePoint.CUSTOMER.Nintex.AdapterLibrary/Layouts/NINTEXWORKFLOW/:

<%@ Page Language="C#" 
    DynamicMasterPageFile="~masterurl/default.master" 
    AutoEventWireup="true" 
    CodeBehind="CopyItemDialog.aspx.cs" 
    EnableEventValidation="false" 
    Inherits="FWI.SharePoint.CFLEX.Nintex.AdapterLibrary.CopyItemDialog, FWI.SharePoint.CFLEX.Nintex.AdapterLibrary, Version=15.0.0.0, Culture=neutral, PublicKeyToken=20f758a8aeaef50b" %>

<%@ Register TagPrefix="Nintex" Namespace="Nintex.Workflow.ServerControls" Assembly="Nintex.Workflow.ServerControls, Version=1.0.0.0, Culture=neutral, PublicKeyToken=913f6bae0ca5ae12" %>
<%@ Register TagPrefix="Nintex" TagName="ConfigurationPropertySection" Src="~/_layouts/15/NintexWorkflow/ConfigurationPropertySection.ascx" %>
<%@ Register TagPrefix="Nintex" TagName="ConfigurationProperty" Src="~/_layouts/15/NintexWorkflow/ConfigurationProperty.ascx" %>
<%@ Register TagPrefix="Nintex" TagName="DialogLoad" Src="~/_layouts/15/NintexWorkflow/DialogLoad.ascx" %>
<%@ Register TagPrefix="Nintex" TagName="DialogBody" Src="~/_layouts/15/NintexWorkflow/DialogBody.ascx" %>
<%@ Register TagPrefix="Nintex" TagName="SingleLineInput" Src="~/_layouts/15/NintexWorkflow/SingleLineInput.ascx" %>
<%@ Register TagPrefix="Nintex" TagName="PlainTextWebControl" Src="~/_layouts/15/NintexWorkflow/PlainTextWebControl.ascx" %>
<%@ Register TagPrefix="Nintex" TagName="ErrorHandlingConfig" Src="~/_layouts/15/NintexWorkflow/ErrorHandlingConfig.ascx" %>

<asp:Content ID="ContentHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
<Nintex:DialogLoad runat="server" />
<script type="text/javascript" src="/_layouts/NintexWorkflow/CustomActions/StartListWorkflow/Scripts/jquery-1.6.2.min.js"></script>
<script type="text/javascript">

    function TPARetrieveConfig() {
        setRTEValue('<%= targetListName.ClientID %>').value = configXml.selectSingleNode("/NWActionConfig/Parameters/Parameter[@Name='TargetListName']/PrimitiveValue/@Value").text;
        LoadErrorHandlingSection();
    }

    function TPAWriteConfig() {
        var targetListNameCtrl = getRTEValue('<%= targetListName.ClientID %>');
        var targetListNameNode = configXml.selectSingleNode("/NWActionConfig/Parameters/Parameter[@Name='TargetListName']/PrimitiveValue/@Value");
        targetListNameNode.text = targetListNameCtrl;

        SaveErrorHandlingSection();
        return true;
    }

    onLoadFunctions[onLoadFunctions.length] = function () {
        dialogSectionsArray["<%= MainControls.ClientID %>"] = true;
    };
</script>
</asp:Content>

<asp:Content ID="ContentBody" ContentPlaceHolderID="PlaceHolderMain" runat="Server">
    <Nintex:DialogBody runat="server" ID="DialogBody" AllowHistoryMessage="true" />

    <Nintex:ConfigurationPropertySection runat="server" ID="MainControls">
        <TemplateRowsArea>
            <Nintex:ConfigurationProperty runat="server" FieldTitle="Target List" RequiredField="true">
                <TemplateControlArea>
                    <Nintex:ListSelector ID="targetListName" runat="server" LibrariesOnly="false" />
                </TemplateControlArea>
            </Nintex:ConfigurationProperty>
            
            <Nintex:ErrorHandlingConfig runat="server" id="errorHandlingConfig1"></Nintex:ErrorHandlingConfig>
        </TemplateRowsArea>
    </Nintex:ConfigurationPropertySection>

</asp:Content>
Codebehind
using Nintex.Workflow.ServerControls;
using System;

namespace FWI.SharePoint.CFLEX.Nintex.AdapterLibrary
{
    public partial class CopyItemDialog : NintexLayoutsBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
    }
}

File is in COMPANY.SharePoint.CUSTOMER.Nintex.AdapterLibrary/Code:

using FWI.SharePoint.CFLEX.Nintex.ActivityLibrary;
using Microsoft.SharePoint;
using Nintex.Workflow;
using Nintex.Workflow.Activities.Adapters;
using System.Collections.Generic;
using System.Workflow.ComponentModel;

namespace FWI.SharePoint.CFLEX.Nintex.AdapterLibrary
{
    public class CopyItemAdapter : GenericRenderingAction
    {
        private const string TargetListNameProperty = "TargetListName";

        public override NWActionConfig GetDefaultConfig(GetDefaultConfigContext context)
        {
            var config = new NWActionConfig(this);
            config.TLabel = ActivityReferenceCollection.FindByAdapter(this).Name;

            config.Parameters = new [] 
            {
                new ActivityParameter
                {
                    Name = TargetListNameProperty, 
                    PrimitiveValue = new PrimitiveValue 
                    {
                        Value = string.Empty, 
                        ValueType = SPFieldType.Text.ToString()
                    }
                }
            };

            config.ErrorHandling = new ErrorHandling();

            return config;
        }

        public override bool ValidateConfig(ActivityContext context)
        {
            bool isValid = true;
            IDictionary<string, ActivityParameterHelper> parameters = context.Configuration.GetParameterHelpers();

            if (!IsTargetListNameParameterSet(context, parameters))
            {
                validationSummary.AddError("Target List", ValidationSummaryErrorType.CannotBeBlank);
                isValid = false;
            }

            return isValid;
        }

        private static bool IsTargetListNameParameterSet(ActivityContext context, IDictionary<string, ActivityParameterHelper> parameters)
        {
            return parameters[TargetListNameProperty].Validate(typeof(string), context);
        }

        public override CompositeActivity AddActivityToWorkflow(PublishContext context)
        {
            IDictionary<string, ActivityParameterHelper> parameters = context.Config.GetParameterHelpers();

            var activity = new CopyItemActivity();

            parameters[TargetListNameProperty].AssignTo(activity, CopyItemActivity.TargetListNameProperty, context);

            activity.SetBinding(CopyItemActivity.__ContextProperty, new ActivityBind(context.ParentWorkflow.Name, StandardWorkflowDataItems.__context));
            activity.SetBinding(CopyItemActivity.__ListItemProperty, new ActivityBind(context.ParentWorkflow.Name, StandardWorkflowDataItems.__item));
            activity.SetBinding(CopyItemActivity.__ListIdProperty, new ActivityBind(context.ParentWorkflow.Name, StandardWorkflowDataItems.__list));

            if (context.Config.ErrorHandling != null)
            {
                context.Config.ErrorHandling.AssignTo(activity, 
                  CopyItemActivity.CaptureErrorsProperty,
                  CopyItemActivity.ErrorOccurredOutputProperty,
                  CopyItemActivity.ErrorMessageOutputProperty,
                  context);
            }

            var flags = new ActivityFlags();
            flags.AddLabelsFromConfig(context.Config);
            flags.AssignTo(activity);

            context.ParentActivity.Activities.Add(activity);
            return null;
        }

        public override NWActionConfig GetConfig(RetrieveConfigContext context)
        {
            NWActionConfig config = GetDefaultConfig(context);

            IDictionary<string, ActivityParameterHelper> parameters = config.GetParameterHelpers();

            parameters[TargetListNameProperty].RetrieveValue(context.Activity, CopyItemActivity.TargetListNameProperty, context);

            config.ErrorHandling = ErrorHandling.BuildFrom(
                context.Activity,
                CopyItemActivity.CaptureErrorsProperty,
                CopyItemActivity.ErrorOccurredOutputProperty,
                CopyItemActivity.ErrorMessageOutputProperty,
                context.Variables);

            return config;
        }

        public override ActionSummary BuildSummary(ActivityContext context)
        {
            IDictionary<string, ActivityParameterHelper> parameters = context.Configuration.GetParameterHelpers();
            return new ActionSummary("Copying item to '{1}'.", parameters[TargetListNameProperty].Value);
        }
    }
}

Erstellen der Nintex Workflow Activity (NWA) Datei

[Bearbeiten | Quelltext bearbeiten]

File is in COMPANY.SharePoint.CUSTOMER.Nintex.AdapterLibrary/ConfigFiles-Project:

<NintexWorkflowActivity>
  <Name>Copy Item</Name>
  <Category>FWI</Category>
  <Description>Copy the current item to a given list</Description>
  <ActivityType>FWI.SharePoint.CFLEX.Nintex.ActivityLibrary.CopyItemActivity</ActivityType>
  <ActivityAssembly>FWI.SharePoint.CFLEX.Nintex.ActivityLibrary, Version=15.0.0.0, Culture=neutral, PublicKeyToken=20f758a8aeaef50b</ActivityAssembly>
  <AdapterType>FWI.SharePoint.CFLEX.Nintex.AdapterLibrary.CopyItemAdapter</AdapterType>
  <AdapterAssembly>FWI.SharePoint.CFLEX.Nintex.AdapterLibrary, Version=15.0.0.0, Culture=neutral, PublicKeyToken=20f758a8aeaef50b</AdapterAssembly>
  <HandlerUrl>ActivityServer.ashx</HandlerUrl>
  <Icon>/_layouts/15/NintexWorkflow/Images/Activities/CopyItemIcon.png</Icon>
  <ToolboxIcon>/_layouts/15/NintexWorkflow/Images/Activities/small/CopyItemIconSmall.png</ToolboxIcon>
  <ConfigurationDialogUrl>CopyItemDialog.aspx</ConfigurationDialogUrl>
  <ShowInCommonActions>no</ShowInCommonActions>
  <DocumentLibrariesOnly>no</DocumentLibrariesOnly>
</NintexWorkflowActivity>
Images

Images are in

COMPANY.SharePoint.CUSTOMER.Nintex.AdapterLibrary/Layouts/NINTEXWORKFLOW/Images/Activities (48×48 px) bzw.
COMPANY.SharePoint.CUSTOMER.Nintex.AdapterLibrary/Layouts/NINTEXWORKFLOW/Images/Activities/Small (32×32 px).

Import der NWA-Datei

[Bearbeiten | Quelltext bearbeiten]
  • Nintex Workflow Management
  • Manage Allowed Actions
  • Add a custom action
  • Import workflow action
  • .NWA-Datei auswählen
  • Activity aktivieren
  • OK