|
|
#1 |
|
Участник
|
Новый Task
Пытаюсь создать новый тас программно в новом приложении,помещенном в C:\Program Files\Microsoft Dynamics CRM Server\CRMWeb\ISV.
код добавления.. Код: CrmAuthenticationToken token = new CrmAuthenticationToken();
token.OrganizationName = sOrgname;
token.AuthenticationType = 0;
//Create the Service
CrmService crmService = new CrmService();
crmService.Credentials = System.Net.CredentialCache.DefaultCredentials;
//crmService.Credentials = new System.Net.NetworkCredential("administrator", "pass@word1", "LITWAREINC");
crmService.CrmAuthenticationTokenValue = token;
string crmurl = (string)(Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\MSCRM").GetValue("ServerUrl")) + "/2007/crmservice.asmx";
crmService.Url = crmurl;
//
string sType = string.Empty;
string sId = string.Empty;
if(Request.Params["typename"]!=null)
{
sType = Request.Params["typename"];
sId = Request.Params["id"];
txtNotes.Text = "sType-" + sType;
txtNotes.Text += "sId-" + sId;
Microsoft.Crm.Sdk.Query.ColumnSet cols = new Microsoft.Crm.Sdk.Query.ColumnSet();
//cols.Attributes = new ArrayList();
cols.Attributes.Add("subject");
Guid gId = new Guid(sId);
lead oLead = (lead)crmService.Retrieve(sType, gId, cols);
txtNotes.Text += "oLead.subject-" + oLead.subject;
string ssubject = oLead.subject;
task t = new task();
//t.prioritycode = new PickList();
//t.prioritycode.Value = Convert.ToInt32("0");
t.subject = "my first task";
t.description = "my first task description";
t.scheduledstart = new CrmDateTime();
t.scheduledstart.Value = DateTime.Now.ToString();
t.scheduledend = new CrmDateTime();
t.scheduledend.Value = DateTime.Now.ToString();
t.regardingobjectid = new Lookup();
//t.regardingobjectid.name = "my name";
t.regardingobjectid.type = EntityName.lead.ToString();
t.regardingobjectid.Value = gId;
//t.ownerid = new Owner();
//t.ownerid.name = "my name";
//t.ownerid.type = "type of object";
//t.ownerid.Value = new Guid();
t.scheduleddurationminutes = new CrmNumber();
t.scheduleddurationminutes.Value = 45;
Guid gTSKId=new Guid();
try
{
gTSKId = crmService.Create(t);
}
catch (System.Web.Services.Protocols.SoapException ex)
{
txtNotes.Text += ex.Detail.InnerText;
}
txtNotes.Text+= "gTSKId-" + gTSKId.ToString();
if(gTSKId!=Guid.Empty)
{
SetStateTaskRequest tr = new SetStateTaskRequest();
tr.EntityId = gTSKId;
tr.TaskState = new TaskState();
tr.TaskState = TaskState.Completed; //(or Canceled,Open);
tr.TaskStatus = -1; //(set this to -1 so that CRM can decide the appropriate status.)
crmService.Execute(tr);
}Единственный толковый ресурс откуда я в общем-то и взял весь код это http://mymscrm3.blogspot.com/2007/12...in-crm-30.html |
|
|
|
|
#2 |
|
Участник
|
Вот мой вариант. Может, почерпнете что-нибудь из этого
string orgName = Request.QueryString["orgname"]; ViewState["orgname"] = orgName; CrmAuthenticationToken token = new CrmAuthenticationToken(); token.AuthenticationType = 0; token.OrganizationName = orgName; CrmService service = new CrmService(); service.CrmAuthenticationTokenValue = token; service.Credentials = System.Net.CredentialCache.DefaultCredentials; Guid userid = new Guid(); WhoAmIRequest userRequest = new WhoAmIRequest(); WhoAmIResponse currentUser = (WhoAmIResponse)service.Execute(userRequest); userid = currentUser.UserId; task task = new task(); //string correctDateTime = "2009-05-08T12:00:00"; string correctDateTime = ""; string year = idDate.Text.Substring(6, 4); string month = idDate.Text.Substring(3, 2); string day = idDate.Text.Substring(0, 2); // Set the task subject. task.subject = subjectText.Text; string time = idTime.SelectedItem.Text; string hour = ""; string minute = ""; hour = time.Substring(0, 2); minute = time.Substring(3, 2); // Set the date of the task. correctDateTime = year + "-" + month + "-" + day + "T" + hour + ":" + minute + ":00"; task.scheduledstart = new CrmDateTime(); task.scheduledstart.Value = correctDateTime; //Set the regardingobject task.regardingobjectid = new Lookup(); task.regardingobjectid.Value = new Guid(regardingobjectidHidden.Value); task.regardingobjectid.type = EntityName.account.ToString(); //Set the user task.ownerid = new Owner(); task.ownerid.Value = user.UserId; task.ownerid.type = EntityName.systemuser.ToString(); if (descriptionText.Text != "") { task.description = descriptionText.Text; } //Try to create the task Guid createdTaskId = service.Create(task); #region check success Boolean success = false; if (createdTaskId != Guid.Empty) { success = true; } Log("Task success " + success); Что-то вроде..... |
|
|
|
|
#3 |
|
Участник
|
Что-то не помогает..все то же самое... 0x80044150 Generic SQL erro
|
|
|
|
|
#4 |
|
Участник
|
Решил покопаться с помощью sql profiler. поочередно запускал все действия во время работы программы. Единственное что не сработало это
"exec sp_executesql N'insert into QueueItemBase(QueueId, OrganizationId, State, Status, ObjectId, ModifiedOn, Priority, CreatedBy, ObjectTypeCode, TimeZoneRuleVersionNumber, EnteredOn, Title, ModifiedBy, QueueItemId, DeletionStateCode, CreatedOn, UTCConversionTimeZoneCode) values (@QueueId0, @OrganizationId0, @State0, @Status0, @ObjectId0, @ModifiedOn0, @Priority0, @CreatedBy0, @ObjectTypeCode0, @TimeZoneRuleVersionNumber0, @EnteredOn0, @Title0, @ModifiedBy0, @QueueItemId0, @DeletionStateCode0, @CreatedOn0, @UTCConversionTimeZoneCode0)',N'@QueueId0 uniqueidentifier,@OrganizationId0 uniqueidentifier,@State0 int,@Status0 int,@ObjectId0 uniqueidentifier,@ModifiedOn0 datetime,@Priority0 int,@CreatedBy0 uniqueidentifier,@ObjectTypeCode0 int,@TimeZoneRuleVersionNumber0 int,@EnteredOn0 datetime,@Title0 ntext,@ModifiedBy0 uniqueidentifier,@QueueItemId0 uniqueidentifier,@DeletionStateCode0 int,@CreatedOn0 datetime,@UTCConversionTimeZoneCode0 int',@QueueId0='00000000-0000-0000-0000-000000000000',@OrganizationId0='00B573ED-1D22-4EF7-8DB1-6016CAA1EB35',@State0=0,@Status0=2,@ObjectId0='50F7396A-6B4F-DE11-84BC-0003FF94D69B',@ModifiedOn0='2009-06-02 11:49:24:000',@Priority0=1,@CreatedBy0='D874E288-2C8C-43D5-AEBA-5404888BC185',@ObjectTypeCode0=4212,@TimeZoneRuleVersionNumber0=0,@EnteredOn0='2009-06-02 11:49:24:000',@Title0=N'subjectText.Text',@ModifiedBy0='D874E288-2C8C-43D5-AEBA-5404888BC185',@QueueItemId0='51F7396A-6B4F-DE11-84BC-0003FF94D69B',@DeletionStateCode0=0,@CreatedOn0='2009-06-02 11:49:24:000',@UTCConversionTimeZoneCode0=0 " Ошибка на все это "Msg 547, Level 16, State 0, Line 1 The INSERT statement conflicted with the FOREIGN KEY constraint "queue_entries". The conflict occurred in database "MicrosoftCRM_MSCRM", table "dbo.QueueBase", column 'QueueId'. The statement has been terminated." Где можно трассировку посомтреть в CRM? |
|
|
|
|
#5 |
|
Участник
|
В трассировке именно то что я в SQL нашел... "System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "queue_entries". The conflict occurred in database "MicrosoftCRM_MSCRM", table "dbo.QueueBase", column 'QueueId'."
|
|
|
|
|
#6 |
|
Участник
|
Заработало..я поменял код создания сервиса
Код: CrmAuthenticationToken token = new CrmAuthenticationToken();
token.OrganizationName = sOrgname;
token.AuthenticationType = 0;
//Create the Service
CrmService crmService = new CrmService();
//crmService.Credentials = System.Net.CredentialCache.DefaultCredentials;
crmService.Credentials = new System.Net.NetworkCredential("administrator", "pass@word1");
crmService.PreAuthenticate = false;
crmService.CrmAuthenticationTokenValue = token;
string crmurl = (string)(Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\MSCRM").GetValue("ServerUrl")) + "/2007/crmservice.asmx";
crmService.Url = crmurl; |
|
|
|
|
#7 |
|
Участник
|
Почему-то не работает код crmService.Credentials = System.Net.CredentialCache.DefaultCredentials; Хотя в моем приложениие есть
<authentication mode="Windows"/> <identity impersonate="true"/> Что такое происходит? |
|
|
|
|
#8 |
|
Чайный пьяница
|
Цитата:
Плюс всю работу с CrmService оберните конструкцией using (new CrmImpersonator()){...}
__________________
Эмо разработчик, сначала пишу код, потом плачу над его несовершенством. Подписывайтесь на мой блог, twitter и YouTube канал. Пользуйтесь моим Ultimate Workflow Toolkit |
|
|
|
|
#9 |
|
Участник
|
Спасибо, помогло!!!
|
|
|
|
|
#10 |
|
Участник
|
К сожалению все таки не работает DefaultCredentials. Я что-то упустил и подумал что настройки конфига сработали. На самом деле как работало через crmService.Credentials = new System.Net.NetworkCredential("administrator", "pass@word1"); так и работает. Есть какой-нить другой способ передать информацию о пользователе св-ву crmService.Credentials? Почему у всех людей работает а у меня нет? Конфиг приложил......
Код сохранения Код: protected void btnSave_Click(object sender, Coolite.Ext.Web.AjaxEventArgs e)
{
if (ValidateActivityDate())
{
using (new CrmImpersonator())
{
string sOrgname = string.Empty;
sOrgname = Request.Params["orgname"];
CrmAuthenticationToken token = new CrmAuthenticationToken();
token.OrganizationName = sOrgname;
token.AuthenticationType = 0;
//Create the Service
CrmService crmService = new CrmService();
crmService.Credentials = System.Net.CredentialCache.DefaultCredentials;
//crmService.Credentials = new System.Net.NetworkCredential("administrator", "pass@word1");
//crmService.Credentials = WindowsIdentity.GetCurrent();
crmService.PreAuthenticate = false;
crmService.CrmAuthenticationTokenValue = token;
crmService.Url = (string)(Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\MSCRM").GetValue("ServerUrl")) + "/2007/crmservice.asmx";
//
string sType = string.Empty;
string sLeadId = string.Empty;
if (Request.Params["typename"] != null && Request.Params["id"] != null)
{
sType = Request.Params["typename"];
sLeadId = Request.Params["id"];
Microsoft.Crm.Sdk.Query.ColumnSet cols = new Microsoft.Crm.Sdk.Query.ColumnSet();
cols.Attributes.Add("subject");
Guid gLeadId = new Guid(sLeadId);
lead oLead = (lead)crmService.Retrieve(sType, gLeadId, cols);
//
Guid userid = new Guid();
WhoAmIRequest userRequest = new WhoAmIRequest();
WhoAmIResponse currentUser = (WhoAmIResponse)crmService.Execute(userRequest);
userid = currentUser.UserId;
task task = new task();
// Set the task subject.
task.subject = txtNotes.Text;
task.scheduledstart = new CrmDateTime();
task.scheduledstart.Value = txtActivity.SelectedDate.ToString("s");
task.actualdurationminutes = new CrmNumber();
task.actualdurationminutes.Value = Convert.ToInt32(ddDuration.SelectedItem.Value);
//Set the regardingobject
task.regardingobjectid = new Lookup();
task.regardingobjectid.Value = oLead.leadid.Value;
task.regardingobjectid.type = EntityName.lead.ToString();
//Set the user
task.ownerid = new Owner();
task.ownerid.Value = userid;
task.ownerid.type = EntityName.systemuser.ToString();
//set created by
task.createdby = new Lookup();
task.createdby.Value = userid;
task.createdby.type = EntityName.systemuser.ToString();
Guid gTSKId = new Guid();
try
{
gTSKId = crmService.Create(task);
lblError.Text = string.Empty;
lblInfo.Text = "\"" + task.subject + "\" Task Added.";
}
catch (System.Web.Services.Protocols.SoapException ex)
{
lblInfo.Text = string.Empty;
lblError.Text += ex.Detail.InnerText + userid.ToString() + " " + sOrgname;
}
}
}
}
}Последний раз редактировалось Kipetcoff; 08.06.2009 в 12:34. |
|
|
|
|
#11 |
|
Участник
|
Опытным путем выяснил что причина в конфликте конструкций using (new CrmImpersonator()) и try catch. Нужно использовать или то или другое. Осталось только понять почему так..
|
|
|
|
|
Похожие темы
|
||||
| Тема | Ответов | |||
| Новый пользователь из другого домена | 27 | |||
| Как лучше реализовать? Создать новый объект или... | 12 | |||
| Plugin на для обновления задачи (Task) | 14 | |||
| связь через новый объект | 3 | |||
| связь через новый объект | 0 | |||
|