我是靠谱客的博主 紧张枫叶,最近开发中收集的这篇文章主要介绍Dynamics Plugin 初始化和常用方法Demo,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

using System;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;

namespace Utility
{
    public class PluginServiceProvider
    {
        public int Index = 1;
        public ITracingService TracingService { get; set; }
        public IPluginExecutionContext Context { get; set; }
        public IOrganizationServiceFactory ServiceFactory { get; set; }
        public IOrganizationService UserService { get; set; }
        public IOrganizationService SysService { get; set; }

        public PluginServiceProvider() { }

        /// <summary>
        /// Plugin的实例,或取Plugin对象。
        /// </summary>
        /// <param name="serviceProvider">Execute IServiceProvider类型的参数</param>
        public PluginServiceProvider(IServiceProvider serviceProvider)
        {
            TracingService = GetService<ITracingService>(serviceProvider);
            Context = GetService<IPluginExecutionContext>(serviceProvider);//上下文
            ServiceFactory = GetService<IOrganizationServiceFactory>(serviceProvider);
            SysService = this.ServiceFactory.CreateOrganizationService(null);//管理员权限
            UserService = this.ServiceFactory.CreateOrganizationService(this.Context.UserId);//用户权限
        }

        /// <summary>
        /// 实体所处状态
        /// </summary>
        /// <param name="entityName">实体名称</param>
        /// <param name="action">create,update,,delete</param>
        /// <param name="state">20(pre),40(post) </param>
        /// <returns></returns>
        public bool EqualEntityName_Action_State(string entityName, string action, int state)
        {
            CheckNull(Context, "IPluginExecutionContext");
            return Context.PrimaryEntityName.ToLower().Equals(entityName.ToLower()) &&
                Context.MessageName.ToLower().Equals(action.ToLower()) && Context.Stage == state;
        }
        /// <summary>
        /// 实体所处状态
        /// </summary>
        /// <param name="state">20(pre),40(post) </param>
        /// <param name="Action">create,update,,delete</param>
        /// <returns></returns>
        public bool EqualAction_Or_MessageName(int state, string Action)
        {
            TracingService.Trace("EqualAction_Or_MessageName");
            if (Context.Stage == state)
            {
                if (Action != null && Action.ToLower() == Context.MessageName.ToLower())
                {
                    return true;
                }
            }

            return false;
        }


        /// <summary>
        /// 判断实体的字段是否为空
        /// </summary>
        /// <param name="en">实体对象</param>
        /// <param name="name">字段name</param>
        /// <returns></returns>
        public bool IsNotNull(Entity en, string name)
        {
            return en.Contains(name) && IsNotNull(en[name]);
        }


        //获取当前用户的语言
        public int? GetCurrentUserLanguageId()
        {
            IOrganizationService service = SysService;
            Guid userid = Context.UserId;
            QueryExpression mySavedQuery = new QueryExpression
            {
                ColumnSet = new ColumnSet("systemuserid", "uilanguageid"),
                EntityName = "usersettings",
                Criteria = new FilterExpression()
                {
                    FilterOperator = Microsoft.Xrm.Sdk.Query.LogicalOperator.And,
                    Conditions =  
                {        
                    new ConditionExpression  
                    {  
                        AttributeName = "systemuserid",  
                        Operator = ConditionOperator.Equal,  
                        Values = {userid}  
                    }  
                }
                }
            };

            EntityCollection ec = service.RetrieveMultiple(mySavedQuery);
            if (ec != null && ec.Entities != null && ec.Entities.Count > 0 && ec.Entities[0].Contains("uilanguageid"))
            {
                return (int)(ec.Entities[0]["uilanguageid"]);
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 插件回滚,弹出消息。
        /// </summary>
        /// <param name="msg">消息类容</param>
        public void MessageShow(string msg)
        {
            throw new InvalidPluginExecutionException(msg);
        }

        /// <summary>
        /// 错误日志
        /// </summary>
        /// <param name="error">错误信息</param>
        /// <param name="filepath">错误信息存储路径</param>
        public static void WriteError(string error, string filepath)
        {
            string logpath = "D:\DXC\interface\crm";
            if (filepath != null && !string.IsNullOrEmpty(filepath)) { logpath = filepath; }
            System.IO.StreamWriter sr;
            string logFilePath = logpath + "_" + DateTime.Today.ToString("yyyy-MM-dd") + ".log";
            if (System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(logFilePath)) == false)
            {
                System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(logFilePath));
            }
            if (System.IO.File.Exists(logFilePath))
            {
                sr = System.IO.File.AppendText(logFilePath);
            }
            else
            {
                sr = System.IO.File.CreateText(logFilePath);
            }
            sr.WriteLine(DateTime.Now.ToString("--------yyyy/MM/dd HH:mm:ss--------"));
            sr.WriteLine(error);
            sr.Close();
        }
 


        public void CheckNull(object o, string name)
        {
            if (o == null)
            {
                throw new InvalidPluginExecutionException(name + " is null!");
            }
        }

      

        public T GetService<T>(IServiceProvider serviceProvider)
        {
            return (T)serviceProvider.GetService(typeof(T));
        }

        public bool IsNotNull(object o)
        {
            return o != null && o != DBNull.Value && !string.IsNullOrEmpty(o.ToString());
        }

        public bool IsEntity()
        {
            CheckNull(Context, "IPluginExecutionContext");
            return Context.InputParameters.Contains("Target");
        }

        public bool EqualCurrentEntity(string name)
        {
            return IsEntity() && GetCurrentEntityName() == name.ToLower();
        }

        public string GetCurrentEntityName()
        {
            CheckNull(Context, "IPluginExecutionContext");
            return Context.PrimaryEntityName.ToLower();
        }
    } 
}

Demo

using System;
using Microsoft.Xrm.Sdk;
using Utility;

namespace ProjectnamechangeManage
{
    public class new_projectnamechange_CreatePre:IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            string entityName = "entityname";
            PluginServiceProvider plugin = new PluginServiceProvider(serviceProvider);
            //实体是创建Post,进入该插件处理事务
            if (!plugin.EqualEntityName_Action_State(entityName, "create", 40))
                return;
            try
            {
                Entity entity = (Entity)plugin.Context.InputParameters["Target"];
                Entity postEnt = null;
                Entity preEnt = null;
                if (plugin.Context.PostEntityImages.Contains(entityName))
                    postEnt = plugin.Context.PostEntityImages[entityName];
                if (plugin.Context.PreEntityImages.Contains(entityName))
                    preEnt = plugin.Context.PreEntityImages[entityName];

                //处理类容
                //code
                
            }
            catch(Exception ex)
            {
                plugin.MessageShow(ex.Message.ToString());
            }
         
        }
    }
}

 

最后

以上就是紧张枫叶为你收集整理的Dynamics Plugin 初始化和常用方法Demo的全部内容,希望文章能够帮你解决Dynamics Plugin 初始化和常用方法Demo所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(32)

评论列表共有 0 条评论

立即
投稿
返回
顶部