Plugin(C#)

分派

AssignRequest assign = new AssignRequest();

assign.Assignee = prEntity["ownerid"] as EntityReference;

assign.Target = new EntityReference("new_budgetused", new_budgetusedId);

_service.Execute(assign);

共享

#region 插件中CRM共享共用方法

/// <summary>

/// 共享

/// </summary>

/// <param name="initentityName">要求共享的实体名称</param>

/// <param name="userId">要求共享的实体GUID</param>

/// <param name="entityName">指定共享的实体名称</param>

/// <param name="entityId">指定共享的实体GUID</param>

/// <param name="service">CRM组织服务</param>

private void ShareEntity(string initentityName, Guid userId, string entityName, Guid entityId, IOrganizationService service)

{

GrantAccessRequest grant = new GrantAccessRequest();

grant.PrincipalAccess = new PrincipalAccess

{

//读、写、附加等权限共享

AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess | AccessRights.AppendAccess,

Principal = new EntityReference(initentityName, userId)//共享给某个用户

};

grant.Target = new EntityReference(entityName, entityId);//要共享的对象

service.Execute(grant);

}

#endregion

取消共享

public void RevokeShareRecords(string LogicName,string targetEntityName,string usedAttrName, IOrganizationService service, Guid targetEntityId,string[] attrs,object[] values,string[] columnSet)

{

QueryByAttribute query = new QueryByAttribute(LogicName);

query.Attributes.AddRange(attrs);

query.Values.AddRange(values);

query.ColumnSet = new ColumnSet(columnSet);

EntityCollection userCollection = service.RetrieveMultiple(query);

foreach (Entity entity in userCollection.Entities)

{

//Guid AttrId = (Guid)entity.Attributes[SegmentInfo.SystemUserId];

Guid UserId = (Guid)entity.Attributes[usedAttrName];

EntityReference er = new EntityReference("systemuser", UserId);

RevokeAccessRequest revokeAccessRequest = new RevokeAccessRequest {

Revokee = new EntityReference("systemuser", UserId),

Target = new EntityReference(targetEntityName, targetEntityId)

};

service.Execute(revokeAccessRequest);

}

}

查询

string fetchxml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>

<entity name='" + objecttype + @"'>

<attribute name='new_name' />

<filter type='and'>

<condition attribute='statecode' operator='eq' value='0' />

<condition attribute='new_name' operator='eq' value='" + name + @"' />

</filter>

</entity>

</fetch>";

EntityCollection entityCollection = service.RetrieveMultiple(new FetchExpression(fetchxml));

获取最顶级的上下文,用于获取当前操作用户

public IPluginExecutionContext GetTopContext(IPluginExecutionContext currentContext)

{

IPluginExecutionContext topContext = currentContext;

for (int i = 0; i <= currentContext.Depth; i++)

{

if (topContext.ParentContext != null)

{

topContext = topContext.ParentContext;

}

}

return topContext;

}

获取sharepoint上的文档

public static DataCollection<Entity> RetrieveSharepointNotes(IOrganizationService service)

{

QueryExpression query = new QueryExpression("annotation")

{

//ColumnSet = new ColumnSet(true),

Criteria =

{

Filters =

{

new FilterExpression(LogicalOperator.Or)

{

Conditions =

{

new ConditionExpression("subject",ConditionOperator.Equal, "Attachment Error"),

},

Filters =

{

new FilterExpression(LogicalOperator.And)

{

Conditions =

{

new ConditionExpression("subject", ConditionOperator.Equal, "File Attachment"),

new ConditionExpression("notetext", ConditionOperator.Like, "http://spark.partners.extranet.microsoft.com%"),

}

}

}

}

}

}

};

EntityCollection ec = service.RetrieveMultiple(query);

return ec.Entities;

}

Query 转化为FetchXML/  FetchXML转化为Query

public static string ConvertQueryToFetchXml(QueryExpression query, IOrganizationService crmService)

{

QueryExpressionToFetchXmlRequest request = new QueryExpressionToFetchXmlRequest();

request.Query = query;

QueryExpressionToFetchXmlResponse response

= (QueryExpressionToFetchXmlResponse)crmService.Execute(request);

return response.FetchXml;

}

public static QueryExpression ConvertFetchXmlToQuery(string fetchXml, IOrganizationService crmService)

{

FetchXmlToQueryExpressionRequest fetchXmlRequest = new FetchXmlToQueryExpressionRequest();

fetchXmlRequest.FetchXml = fetchXml;

FetchXmlToQueryExpressionResponse fetchXmlResponse

= (FetchXmlToQueryExpressionResponse)crmService.Execute(fetchXmlRequest);

return fetchXmlResponse.Query;

}

获取optionset字段的显示名

//string name  = GetPickListText("opportunity", "new_opportunitystate", 0, service);

public static string GetPickListText(string entityName, string attributeName, int optionSetValue, IOrganizationService service)

{

string AttributeName = attributeName;

string EntityLogicalName = entityName;

RetrieveEntityRequest retrieveDetails = new RetrieveEntityRequest();

retrieveDetails.EntityFilters = EntityFilters.All;

retrieveDetails.LogicalName = EntityLogicalName;

RetrieveEntityResponse retrieveEntityResponseObj = (RetrieveEntityResponse)service.Execute(retrieveDetails);

EntityMetadata metadata = retrieveEntityResponseObj.EntityMetadata;

PicklistAttributeMetadata picklistMetadata = metadata.Attributes.FirstOrDefault(attribute => String.Equals(attribute.LogicalName, attributeName, StringComparison.OrdinalIgnoreCase)) as PicklistAttributeMetadata;

OptionSetMetadata options = picklistMetadata.OptionSet;

IList<OptionMetadata> picklistOption = (from o in options.Options where o.Value.Value == optionSetValue select o).ToList();

string picklistLabel = (picklistOption.First()).Label.UserLocalizedLabel.Label;

return picklistLabel;

}

改变记录的状态

public static void ChangeRecordState(IOrganizationService service, EntityReference entityMoniker, OptionSetValue state, OptionSetValue status)

{

SetStateRequest req = new SetStateRequest

{

EntityMoniker = entityMoniker,

State = state,

Status = status

};

service.Execute(req);

}

从template创建邮件

public static void CreateEmailFromTemplate(IOrganizationService service, EntityCollection sendFromCol, EntityCollection sendToCol, string emailSubject, string previewTriggerVaule, EntityReference regard, Guid contactId, Entity template, string btnOrder)

{

if (template != null)

{

// Use the InstantiateTemplate message to create an e-mail message using a template.

InstantiateTemplateRequest instTemplateReq = new InstantiateTemplateRequest

{

TemplateId = template.Id,

ObjectId = contactId,

ObjectType = "contact"

};

InstantiateTemplateResponse instTemplateResp = (InstantiateTemplateResponse)service.Execute(instTemplateReq);

Entity email = instTemplateResp.EntityCollection.Entities[0];

email.Attributes["new_campaigninvatationid"] = previewTriggerVaule;

email.Attributes["subject"] = emailSubject;

email.Attributes.Add("from", sendFromCol);

service.Create(email);

}

}

查询N:N记录

public static EntityCollection RetrieveNNRecords(IOrganizationService service, Guid ToEntityId, string FromEntity, string ToEntity, string RelationShip)

{

QueryExpression qe = new QueryExpression()

{

EntityName = FromEntity,

ColumnSet = new ColumnSet(true),

Criteria =

{

FilterOperator = LogicalOperator.And,

Conditions =

{

new ConditionExpression("statecode",ConditionOperator.Equal,0)

}

},

LinkEntities =

{

new LinkEntity()

{

LinkFromEntityName = FromEntity,

LinkToEntityName = RelationShip,

LinkFromAttributeName = FromEntity+"id",

LinkToAttributeName = FromEntity+"id",

EntityAlias = RelationShip,

Columns = new ColumnSet(),

JoinOperator = JoinOperator.Inner,

LinkEntities =

{

new LinkEntity()

{

LinkFromEntityName = FromEntity,

LinkToEntityName = ToEntity,

LinkFromAttributeName = ToEntity+"id",

LinkToAttributeName = ToEntity+"id",

EntityAlias =ToEntity,

Columns = new ColumnSet(),

JoinOperator = JoinOperator.Inner,

LinkCriteria = new FilterExpression

{

Conditions =

{

new ConditionExpression

{

AttributeName = ToEntity+"id",

Operator = ConditionOperator.Equal,

Values = {

ToEntityId

}

}

}

}

}

}

}

}

};

return service.RetrieveMultiple(qe);

}

}

用户是否有指定的security role

public static bool UserHaveSpeficySecurityRole(IOrganizationService service, string roleName, Guid userID)

{

bool result = false;

QueryExpression query = new QueryExpression()

{

EntityName = "role",

ColumnSet = new ColumnSet(),

Criteria = new FilterExpression { FilterOperator = LogicalOperator.And, Conditions = { newConditionExpression { AttributeName = "name", Operator = ConditionOperator.Equal, Values = { roleName } } } },

LinkEntities =

{

new LinkEntity

{

LinkFromEntityName = "role",

LinkFromAttributeName = "roleid",

LinkToEntityName = "systemuserroles",

LinkToAttributeName = "roleid",

LinkCriteria = new FilterExpression

{

FilterOperator = LogicalOperator.And,

Conditions =

{

new ConditionExpression

{

AttributeName = "systemuserid",

Operator = ConditionOperator.Equal,

Values = { userID}

}

}

}

}

}

};

EntityCollection resultColl = service.RetrieveMultiple(query);

result = resultColl.Entities.Count > 0 ? true : false;

return result;

}

查询一条记录分派给哪些用户

public static List<EntityReference> RetrieveSharedPrincipalsAndAccess(IOrganizationService service, EntityReference entityRef)

{

try

{

var accessRequest = new RetrieveSharedPrincipalsAndAccessRequest

{

Target = entityRef

};

RetrieveSharedPrincipalsAndAccessResponse accessResponse = (RetrieveSharedPrincipalsAndAccessResponse)service.Execute(accessRequest);

List<EntityReference> accessList = null;

if (accessResponse != null && accessResponse.PrincipalAccesses.Length > 0)

{

accessList = new List<EntityReference>();

for (int i = 0; i < accessResponse.PrincipalAccesses.Length; i++)

{

EntityReference accessOwner = accessResponse.PrincipalAccesses[i].Principal;

accessList.Add(accessOwner);

}

}

return accessList;

}

catch (Exception e)

{

throw new Exception("Customized Plugin RetrieveSharedPrincipalsAndAccess Error: " + e.Message);

}

}

拿到拥有指定security role的所有用户

public static ArrayList getUsersinRole(string Role_Name, IOrganizationService service)

{

ArrayList usersinrole = new ArrayList();

StringBuilder fetch2 = new StringBuilder();

fetch2.Append("<fetch mapping='logical' count='50' version='1.0'> ");

fetch2.Append(" <entity name='systemuser'>");

fetch2.Append(" <attribute name='fullname'/> ");

fetch2.Append("     <link-entity name='systemuserroles' to='systemuserid' from='systemuserid'> ");

fetch2.Append("         <link-entity name='role' to='roleid' from='roleid'> ");

fetch2.Append("                <filter> ");

fetch2.Append("                     <condition attribute='name' operator='eq' value='" + Role_Name + "'/> ");

fetch2.Append("                 </filter> ");

fetch2.Append("         </link-entity> ");

fetch2.Append("     </link-entity>");

fetch2.Append(" </entity> ");

fetch2.Append("</fetch>");

EntityCollection result = service.RetrieveMultiple(new FetchExpression(fetch2.ToString()));

foreach (var c in result.Entities)

{

usersinrole.Add(c.Attributes["fullname"].ToString());

}

return usersinrole;

}

判断用户是否是某团队的一员

public bool IsMemberInTeam(IOrganizationService service, Guid teamId, Guid memberId)

{

OrganizationServiceContext context = new OrganizationServiceContext(service);

var query = from relationship in context.CreateQuery("teammembership")

where relationship.GetAttributeValue<Guid>("teamid") == teamId

&& relationship.GetAttributeValue<Guid>("systemuserid") == memberId

select relationship;

return query.FirstOrDefault() != null;

}

添加用户到一个团队

OrganizationRequest request = new AddMembersTeamRequest { MemberIds = new Guid[] { user.Id }, TeamId = team.Id };

var response = service.Execute(request) as AddMembersTeamResponse;

C# 分页查询记录

public static void DoTest(IOrganizationService service)

{

//  Query using the paging cookie.

// Define the paging attributes.

// The number of records per page to retrieve.

int fetchCount = 20;

// Initialize the page number.

int pageNumber = 1;

// Define the order expression to retrieve the records.

OrderExpression order = new OrderExpression();

order.AttributeName = "name";

order.OrderType = OrderType.Ascending;

// Create the query expression and add condition.

QueryExpression pagequery = new QueryExpression();

pagequery.EntityName = "opportunity";

// pagequery.Criteria.AddCondition(pagecondition);

pagequery.Orders.Add(order);

pagequery.ColumnSet.AddColumns();

// Assign the pageinfo properties to the query expression.

pagequery.PageInfo = new PagingInfo();

pagequery.PageInfo.Count = fetchCount;

pagequery.PageInfo.PageNumber = pageNumber;

// The current paging cookie. When retrieving the first page,

// pagingCookie should be null.

pagequery.PageInfo.PagingCookie = null;

while (true)

{

// Retrieve the page.

EntityCollection results = service.RetrieveMultiple(pagequery);

if (results.Entities != null)

{

for (int i = 0; i < results.Entities.Count;i++ )

{

Console.WriteLine(" {0} {1}", results.Entities[i].Id, i + 1);

}

}

// Check for more records, if it returns true.

if (results.MoreRecords)

{

// Increment the page number to retrieve the next page.

pagequery.PageInfo.PageNumber++;

// Set the paging cookie to the paging cookie returned from current results.

pagequery.PageInfo.PagingCookie = results.PagingCookie;

}

else

{

// If no more records are in the result nodes, exit the loop.

break;

}

}

}

更新用户所在的业务部门

SetBusinessSystemUserRequest req = new SetBusinessSystemUserRequest();

req.BusinessId = Guid.Parse("52A18602-09B8-E511-80C2-807DB137DB06"); BU的GUID

req.UserId = Guid.Parse("7F038A46-5BB4-E511-80C6-DD48FB4179EC"); User的GUID

req.ReassignPrincipal = new EntityReference("systemuser", Guid.Parse("7F038A46-5BB4-E511-80C6-DD48FB4179EC")); User的GUID

service.Execute(req);

Dynamics CRM 常用 C# 方法集合的更多相关文章

  1. Dynamics CRM 常用 JS 方法集合

    JS部分 拿到字段的值 var value= Xrm.Page.getAttribute("attributename").getValue(); Xrm.Page.getAttr ...

  2. Microsoft Dynamics CRM 常用JS语法(已转成vs2017语法提示)

    背景 最近接触到Microsoft Dynamics CRM的开发.前端js是必不可少的部分,奈何没有一个语法提示,点不出来后续的语句. 在vscode上面搜索插件的时候发现,有一个大神写的插件htt ...

  3. Microsoft Dynamics CRM4.0 和 Microsoft Dynamics CRM 2011 JScript 方法对比

    CRM 2011 如果需要再IE里面调试,可以按F12在前面加上contentIFrame,比如 contentIFrame.document.getElementById("字段" ...

  4. Dynamics CRM 常用的JS

    常用JS(一) Xrm.Page.context.getUserId():       //获取当前用户id Xrm.Page.context.getUserName():       //获取当前用 ...

  5. javascript技巧及常用事件方法集合(全)

    事件源对象 event.srcElement.tagName event.srcElement.type 捕获释放 event.srcElement.setCapture();  event.srcE ...

  6. Dynamics CRM plugin调试方法之Profiler

    https://blog.csdn.net/vic0228/article/details/72903815

  7. c#一些常用的方法集合

    是从一个asp.net mvc的项目里看到的.挺实用的. 通过身份证号码获取出生日期和性别 通过身份证号码获取出生日期和性别 #region 由身份证获得出生日期 public static stri ...

  8. 常用js方法集合

    var func={ //对象转jsonstring getJsonStr: function(jsonObj) { var temp = []; for (var key in jsonObj) { ...

  9. Microsoft Dynamics CRM 2011的组织服务中的RetrieveMultiple方法(转)

    本篇文章,介绍Microsoft Dynamics CRM 2011的组织服务中的RetrieveMultiple方法. RetreiveMultiple方法,用于获取实体的多个实例,该方法的签名如下 ...

随机推荐

  1. css布局&初始化&基准样式

    学习css布局比较好的网站 学习css布局 1.css设置模块 typography(字体) colour(颜色) link(链接) forms(表单) layout(布局) navigation(导 ...

  2. python模块基础之getpass模块

    getpass模块提供了可移植的密码输入,一共包括下面两个函数: 1. getpass.getpass() 2. getpass.getuser() getpass.getpass([prompt[, ...

  3. winform摄像头拍照 C#利用摄像头拍照

    这是我的第一篇博文,决定以后每个程序都要记录下来,方便以后查阅! 本人小菜一名,本程序也是查阅了网上各位前辈的博客和百度知道所整理出来的一个小程序. 第一次写有点不知道从何写起,先贴一张程序图吧. 程 ...

  4. C语言学习笔记---谭浩强

    前段时间有机会去面试了一次,真是备受“打击”(其实是启发),总的来说就是让我意识到了学习工具和学习技术的区别.所以最近在看一些数据结构和算法,操作系统,python中的并行编程与异步编程等东西.然而数 ...

  5. Oracle除去换行符的方法

    Oracle除去换行符的方法   很多数据存进数据库后,可能需要将整条数据取出,并用特殊 符号分割,而且整条数据必须是处于一行,如此,如果数据出现 换行的情况,那么读取时就有问题.     这个时候就 ...

  6. Android小试牛刀之遇到的问题

    1.运行出错 创建项目时没有使用Empty Activity,创建. 2.创建第一个工程 选择Empty Activity才会自动创建Hello Word代码块 3.appcompat_v7的说明 在 ...

  7. MySql多条SQL语句的批量处理

    pstmt= conn.prepareStatement(sql); for(int i=0;i<500;i++) { //准备sql语句 pstmt.setString(1, "tt ...

  8. POJ3484 Showstopper (二分+字符串处理)

    POJ3484 Showstopper 题目大意: 每次给出三个数x,y,z,用这三个数构成一个等差数列,x为首项,y是末项,z是公差 总共给出n组x,y,z( n待定),求这n组数列中出现次数为奇数 ...

  9. OpenSceneGraph FAQ

    转自http://www.cnblogs.com/indif/archive/2011/04/22/2024805.html 1.地球背面的一个点,计算它在屏幕上的坐标,能得到吗? 不是被挡住了吗? ...

  10. AJAX 跨域

    1.说到ajax就会遇到的两个问题 1.1AJAX以何种格式来交换数据                    1.自定义字符串 2.XML描述 3.JSON描述(建议使用)          1.2如 ...