本文整理汇总了C#中OrganizationService.Execute方法的典型用法代码示例。如果您正苦于以下问题:C# OrganizationService.Execute方法的具体用法?C# OrganizationService.Execute怎么用?C# OrganizationService.Execute使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类OrganizationService
的用法示例。
在下文中一共展示了OrganizationService.Execute方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: FindPluginAssembly
private static Guid FindPluginAssembly(OrganizationService service, string assemblyName)
{
var query = new QueryExpression
{
EntityName = "pluginassembly",
ColumnSet = null,
Criteria = new FilterExpression()
};
query.Criteria.AddCondition("name", ConditionOperator.Equal, assemblyName);
var request = new RetrieveMultipleRequest
{
Query = query
};
var response = (RetrieveMultipleResponse)service.Execute(request);
if (response.EntityCollection.Entities.Count == 1)
{
var id = response.EntityCollection[0].GetAttributeValue<Guid>("pluginassemblyid");
_logger.Log(LogLevel.Debug, () => string.Format("Found id {0} for assembly", id));
return id;
}
return Guid.Empty;
}
示例2: Validate
public override DTSExecResult Validate(IDTSInfoEvents infoEvents)
{
// プロパティが一つでも空だったらエラーとする
if (!PropertiesValidate(infoEvents, URL, Domain, UserName, Password))
{
return DTSExecResult.Failure;
}
// 接続テスト
try
{
var con = CrmConnection.Parse(ConnectionString);
con.Timeout = TimeSpan.FromSeconds(30);
using (var service = new OrganizationService(con))
{
service.Execute<WhoAmIResponse>(new WhoAmIRequest());
}
}
catch (Exception e)
{
infoEvents.FireError(0, "Dynamics CRM 2011 接続マネージャー", e.Message, string.Empty, 0);
return DTSExecResult.Failure;
}
return DTSExecResult.Success;
}
示例3: btnTest_Click
/// <summary>
/// 接続テスト
/// </summary>
/// <param name="sender"></param>
/// <param name="ev"></param>
private void btnTest_Click(object sender, EventArgs ev)
{
var connectionString = CreateConnectionString
(
Url => txbURL.Text,
Domain => txbDomain.Text,
Username => txbUserName.Text,
Password => txbPassword.Text
);
// connection test
try
{
var con = CrmConnection.Parse(connectionString);
con.Timeout = TimeSpan.FromSeconds(30);
using (var service = new OrganizationService(con))
{
service.Execute<WhoAmIResponse>(new WhoAmIRequest());
}
}
catch (Exception e)
{
MessageBox.Show(e.Message, "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
MessageBox.Show("OK", "確認", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
示例4: PublishInCRM
public void PublishInCRM(ServiceRequest serviceRequest)
{
//Connects to the database and Logs the User In
var connection = ConnectToDatabase();
var service = new OrganizationService(connection);
var context = new CrmOrganizationServiceContext(connection);
//const int hour = 60;
EventLog.saveMessage("PublishIssue SRID:" + serviceRequest.SRID);
//Creating the new Case
Entity incident = new Entity("incident");
try
{
//Filling the Data for the new case
incident["createdon"] = serviceRequest.RegistrationDate;
incident["description"] = serviceRequest.LongDescription;
incident["statuscode"] = ReturnStatusCode(serviceRequest.ServiceRequestStatus);
incident["subjectid"] = ReturnRequestType(serviceRequest.ServiceRequestType);
incident["new_moduleoptionset"] = ReturnModuleCode("TS");
//incident["ownerid"] = new EntityReference("systemuser", findConsultantID(serviceRequest.AssignedPerson, service));
incident["new_caseasignedto"] = serviceRequest.AssignedPerson;
incident["new_statushistory"] = serviceRequest.CommentsMatricia;
incident["casetypecode"] = returnRequestKind(serviceRequest.ServiceRequestKind);
incident["followupby"] = serviceRequest.DueDate;
incident["new_supportrequestid"] = serviceRequest.SRID;
incident["title"] = serviceRequest.AssignedToClient + " " + serviceRequest.SRID + " " + serviceRequest.companyName;
//incident["customerid"] = new EntityReference("account", findCustomer((string)serviceRequest.companyName, service));
incident["customerid"] = new EntityReference("account", findCustomerID(serviceRequest.companyName));
incident["new_statushistory"] = serviceRequest.ShortDescription;
incident["new_assignedfrom"] = serviceRequest.CreatedBy;
Guid consultantID = findConsultantID(serviceRequest.AssignedPerson, service);
//Adding the created case to CRM;
var incidentGuid = service.Create(incident);
//Assign a case!
EventLog.saveMessage("Start of Assignment! to :" + consultantID);
AssignRequest assignRequest = new AssignRequest();
assignRequest.Assignee = new EntityReference("systemuser", consultantID);
assignRequest.Target = new EntityReference(incident.LogicalName, incidentGuid);
service.Execute(assignRequest);
}
catch (Exception)
{
EventLog.saveMessage("This case was not created in CRM " + serviceRequest.CreatedBy + "'" + serviceRequest.SRID); ;
}
}
示例5: TestMethod1
public void TestMethod1()
{
IOrganizationService service = new OrganizationService(new CrmConnection("CRM"));
RetrieveFormXmlRequest request = new RetrieveFormXmlRequest();
request.EntityName = "contact";
var response = service.Execute<RetrieveFormXmlResponse>(request);
Console.WriteLine(response.FormXml);
}
示例6: DynamicsCls
/// <summary>
/// コンストラクタ。dynamicsとの接続を確立する。
/// </summary>
/// <param name="user"></param>
/// <param name="pass"></param>
/// <param name="url"></param>
public DynamicsCls(string user, string pass, string url)
{
string connetString = String.Format("Url={0}; Username={1}; Password={2};",
url,
user,
pass);
CrmConnection connection = CrmConnection.Parse(connetString);
_service = new OrganizationService(connection);
WhoAmIResponse res = (WhoAmIResponse)_service.Execute(new WhoAmIRequest());
}
示例7: Validate
/// <summary>
/// Validate method to attempt to connect to CRM with supplied username/password and then execute a whoami request
/// </summary>
/// <param name="username">crm username</param>
/// <param name="password">crm password</param>
public override void Validate(string username, string password)
{
//get the httpcontext so we can store the user guid for impersonation later
HttpContext context = HttpContext.Current;
//if username or password are null, obvs we can't continue
if (null == username || null == password)
{
throw new ArgumentNullException();
}
//get the crm connection
Microsoft.Xrm.Client.CrmConnection connection = CrmUtils.GetCrmConnection(username, password);
//try the whoami request
//if it fails (user can't be authenticated, is disabled, etc.), the client will get a soap fault message
using (OrganizationService service = new OrganizationService(connection))
{
try
{
WhoAmIRequest req = new WhoAmIRequest();
WhoAmIResponse resp = (WhoAmIResponse)service.Execute(req);
Entity systemuser = CrmUtils.GetSystemUser(resp.UserId, service);
CrmIdentity crmIdentity = new CrmIdentity();
crmIdentity.Name = (string)systemuser["fullname"];
crmIdentity.FirstName = (string)systemuser["firstname"];
crmIdentity.LastName = (string)systemuser["lastname"];
crmIdentity.Email = (string)systemuser["internalemailaddress"];
crmIdentity.UserId = resp.UserId;
crmIdentity.SetAuthenticated(true);
List<string> roles = CrmUtils.GetUserRoles(resp.UserId, service);
foreach (string role in roles)
{
crmIdentity.AddRole(role);
}
context.User = new GenericPrincipal(crmIdentity, roles.ToArray());
}
catch (System.ServiceModel.Security.MessageSecurityException ex)
{
throw new FaultException(ex.Message);
}
catch (Exception ex)
{
throw new FaultException(ex.Message);
}
}
}
示例8: GetAuditDetails
/// <summary>
/// Returns a valid List of all audit records for a case
/// </summary>
/// <remarks>
/// Microsoft article on how to retrieve audit history data:
/// https://msdn.microsoft.com/en-us/library/gg309735.aspx
/// </remarks>
/// <param name="guid"></param>
/// <param name="entityLogicalName"></param>
/// <param name="fallbackCreatedOn"></param>
/// <param name="fallbackTicketNumber"></param>
/// <param name="fallbackDueDate"></param>
/// <param name="fallbackOwner"></param>
/// <param name="svc"></param>
/// <returns>List of AuditDataChange</returns>
public List<AuditDataChange> GetAuditDetails(Guid guid, string entityLogicalName)
{
try
{
var auditDataChangeList = new List<AuditDataChange>();
RetrieveRecordChangeHistoryResponse changeResponse;
RetrieveRecordChangeHistoryRequest changeRequest = new RetrieveRecordChangeHistoryRequest();
changeRequest.Target = new EntityReference(entityLogicalName, guid);
AuditDetailCollection details;
using (OrganizationService svc = new OrganizationService(new CrmConnection("Crm")))
{
changeResponse = (RetrieveRecordChangeHistoryResponse)svc.Execute(changeRequest);
}
if (changeResponse != null)
{
details = changeResponse.AuditDetailCollection;
}
else
{
throw new Exception("change response was null?");
}
if (details != null)
{
// filter thru AuditDetailCollection and build List<AuditDataChange>
auditDataChangeList = _ProcessAuditDetails(details);
}
return auditDataChangeList;
}
catch (Exception ex)
{
Util.WriteErrorToLog("GetAuditDetails", new Dictionary<string, string>()
{
{ "guid", guid.ToString() },
{ "entityLogicalName", entityLogicalName }
}, ex);
throw ex;
}
}
示例9: TestConnection
public void TestConnection(string connectionString)
{
try
{
var crmConnection = CrmConnection.Parse(connectionString);
//to escape "another assembly" exception
crmConnection.ProxyTypesAssembly = Assembly.GetExecutingAssembly();
OrganizationService orgService;
using (orgService = new OrganizationService(crmConnection))
{
orgService.Execute(new WhoAmIRequest());
ConnectionString = connectionString;
Close();
}
}
catch (Exception ex)
{
ConnectionStatusLabel.Dispatcher.BeginInvoke(new Action(() => ConnectionStatusLabel.Content = "Connection Failed."));
}
}
示例10: Validate
/// <summary>
/// Validate method to attempt to connect to CRM with supplied username/password and then execute a whoami request
/// </summary>
/// <param name="username">crm username</param>
/// <param name="password">crm password</param>
public override void Validate(string username, string password)
{
//get the httpcontext so we can store the user guid for impersonation later
HttpContext context = HttpContext.Current;
//if username or password are null, obvs we can't continue
if (null == username || null == password)
{
throw new ArgumentNullException();
}
//get the crm connection using the simplified connection string method
// the following assumes the server url is stored in the web.config appsettings collection like so:
// <add key="crmconnectionstring" value="Url=https://crm.example.com; "/>
string connectionString = ConfigurationManager.AppSettings["crmconnectionstring"];
connectionString += " Username=" + username + "; Password=" + password;
Microsoft.Xrm.Client.CrmConnection connection = CrmConnection.Parse(connectionString);
//try the whoami request
//if it fails (user can't be authenticated, is disabled, etc.), the client will get a soap fault message
using (OrganizationService service = new OrganizationService(connection))
{
try
{
WhoAmIRequest req = new WhoAmIRequest();
WhoAmIResponse resp = (WhoAmIResponse)service.Execute(req);
List<string> roles = GetUserRoles(resp.UserId, service);
context.User = new GenericPrincipal(new GenericIdentity(resp.UserId.ToString()), roles.ToArray());
}
catch (System.ServiceModel.Security.MessageSecurityException ex)
{
throw new FaultException(ex.Message);
}
catch (Exception ex)
{
throw new FaultException(ex.Message);
}
}
}
示例11: ChangeStateCode
private static bool? ChangeStateCode(Guid id)
{
var service = new OrganizationService(connection);
SetStateRequest state = new SetStateRequest();
state.State = new OptionSetValue((int)TaskState.Completed);
state.Status =
new OptionSetValue(5);
state.EntityMoniker = new EntityReference()
{
Id = id,
LogicalName = SoftLine.Models.Task.EntityLogicalName
};
SetStateResponse stateSet = (SetStateResponse)service.Execute(state);
SoftLine.Models.Task task =
service.Retrieve(SoftLine.Models.Task.EntityLogicalName, id, new ColumnSet("statecode")).ToEntity<SoftLine.Models.Task>();
if (task.StateCode == TaskState.Completed)
{
return true;
}
return null;
}
示例12: ExecuteButton_Click
private void ExecuteButton_Click(object sender, RoutedEventArgs e)
{
var fetchXml = FetchXmlTextBox.Text;
var crmConnection = CrmConnection.Parse(_connectionString);
//to escape "another assembly" exception
crmConnection.ProxyTypesAssembly = Assembly.GetExecutingAssembly();
try
{
using (var organizationService = new OrganizationService(crmConnection))
{
FetchXmlToQueryExpressionRequest req = new FetchXmlToQueryExpressionRequest {FetchXml = fetchXml};
var response = (FetchXmlToQueryExpressionResponse) organizationService.Execute(req);
new ShowDataWindow(response).ShowDialog();
}
}
catch (Exception ex)
{
MessageBox.Show("Not Connected!" + ex);
}
}
示例13: UpdateTheWebresource
private void UpdateTheWebresource(string selectedFilePath, string connectionString)
{
try
{
OrganizationService orgService;
var crmConnection = CrmConnection.Parse(connectionString);
//to escape "another assembly" exception
crmConnection.ProxyTypesAssembly = Assembly.GetExecutingAssembly();
using (orgService = new OrganizationService(crmConnection))
{
var isCreateRequest = false;
var fileName = Path.GetFileName(selectedFilePath);
var choosenWebresource = GetWebresource(orgService, fileName);
AddLineToOutputWindow("Connected to : " + crmConnection.ServiceUri);
if (choosenWebresource == null)
{
AddErrorLineToOutputWindow("Error : Selected file is not exist in CRM.");
AddLineToOutputWindow("Creating new webresource..");
var createWebresoruce = new CreateWebResourceWindow(fileName);
createWebresoruce.ShowDialog();
if (createWebresoruce.CreatedWebResource == null)
{
AddLineToOutputWindow("Creating new webresource is cancelled.");
return;
}
isCreateRequest = true;
choosenWebresource = createWebresoruce.CreatedWebResource;
}
choosenWebresource.Content = GetEncodedFileContents(selectedFilePath);
if (isCreateRequest)
{
//create function returns, created webresource's guid.
choosenWebresource.Id = orgService.Create(choosenWebresource);
AddLineToOutputWindow("Webresource is created.");
}
else
{
AddLineToOutputWindow("Updating to Webresource..");
var updateRequest = new UpdateRequest
{
Target = choosenWebresource
};
orgService.Execute(updateRequest);
AddLineToOutputWindow("Webresource is updated.");
}
AddLineToOutputWindow("Publishing the webresource..");
var prequest = new PublishXmlRequest
{
ParameterXml = string.Format("<importexportxml><webresources><webresource>{0}</webresource></webresources></importexportxml>", choosenWebresource.Id)
};
orgService.Execute(prequest);
AddLineToOutputWindow("Webresource is published.");
}
_myStopwatch.Stop();
AddLineToOutputWindow(string.Format("Time : " + _myStopwatch.Elapsed));
}
catch (Exception ex)
{
AddErrorLineToOutputWindow("Error : " + ex.Message);
}
}
示例14: UpdateAndPublishSingle
private void UpdateAndPublishSingle(CrmConnection connection, ProjectItem projectItem, Guid webResourceId)
{
try
{
_dte.StatusBar.Text = "Updating & publishing web resource...";
_dte.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationDeploy);
using (OrganizationService orgService = new OrganizationService(connection))
{
string publishXml = "<importexportxml><webresources>";
Entity webResource = new Entity("webresource") { Id = webResourceId };
string extension = Path.GetExtension(projectItem.FileNames[1]);
string content = extension != null && (extension.ToUpper() != ".TS")
? File.ReadAllText(projectItem.FileNames[1])
: File.ReadAllText(Path.ChangeExtension(projectItem.FileNames[1], ".js"));
webResource["content"] = EncodeString(content);
UpdateRequest request = new UpdateRequest { Target = webResource };
orgService.Execute(request);
_logger.WriteToOutputWindow("Uploaded Web Resource", Logger.MessageType.Info);
publishXml += "<webresource>{" + webResource.Id + "}</webresource>";
publishXml += "</webresources></importexportxml>";
PublishXmlRequest pubRequest = new PublishXmlRequest { ParameterXml = publishXml };
orgService.Execute(pubRequest);
_logger.WriteToOutputWindow("Published Web Resource", Logger.MessageType.Info);
}
}
catch (FaultException<OrganizationServiceFault> crmEx)
{
_logger.WriteToOutputWindow("Error Updating And Publishing Web Resource To CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error);
}
catch (Exception ex)
{
_logger.WriteToOutputWindow("Error Updating And Publishing Web Resource To CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error);
}
_dte.StatusBar.Clear();
_dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy);
}
示例15: Connect_Click
private void Connect_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(Name.Text))
{
MessageBox.Show("Enter A Name");
return;
}
if (string.IsNullOrEmpty(ConnString.Text))
{
MessageBox.Show("Enter A Connection String");
return;
}
try
{
CrmConnection connection = CrmConnection.Parse(ConnString.Text);
using (OrganizationService orgService = new OrganizationService(connection))
{
WhoAmIRequest wRequest = new WhoAmIRequest();
WhoAmIResponse wResponse = (WhoAmIResponse)orgService.Execute(wRequest);
OrgId = wResponse.OrganizationId.ToString();
RetrieveVersionRequest vRequest = new RetrieveVersionRequest();
RetrieveVersionResponse vResponse = (RetrieveVersionResponse)orgService.Execute(vRequest);
Version = vResponse.Version;
ConnectionName = Name.Text;
ConnectionString = ConnString.Text;
DialogResult = true;
Close();
}
}
catch (Exception)
{
//TODO: handle error
MessageBox.Show("Error Connecting to CRM");
}
}