AXForum  
Вернуться   AXForum > Microsoft Dynamics CRM > Dynamics CRM: Разработка
All
Забыли пароль?
Зарегистрироваться Правила Справка Пользователи Сообщения за день Поиск

 
 
Опции темы Поиск в этой теме Опции просмотра
Старый 01.06.2009, 18:07   #1  
Kipetcoff is offline
Kipetcoff
Участник
 
136 / 16 (1) ++
Регистрация: 20.05.2009
Адрес: Санкт-Петербург
Новый 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);
			  }
Так вот на все это безобразие ругается 0x80044150 Generic SQL error. Гугл на это выдает много разного,но чаще всего э то касается ошибки при бобавлении e-mail activities. Я же добавляю таск. Я вычитал что можно где-то посмотреть eventview. У самого сервера в ивентах ничего нет по этой ошибке. Где ивенты та смотерть? Может я просто что-то не то определил. Активити у меня определяется для leads. Я правльно привязываю их к leads?
Единственный толковый ресурс откуда я в общем-то и взял весь код это http://mymscrm3.blogspot.com/2007/12...in-crm-30.html
Старый 02.06.2009, 12:58   #2  
BSvetlana is offline
BSvetlana
Участник
 
27 / 10 (1) +
Регистрация: 13.03.2009
Вот мой вариант. Может, почерпнете что-нибудь из этого

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);


Что-то вроде.....
Старый 02.06.2009, 15:10   #3  
Kipetcoff is offline
Kipetcoff
Участник
 
136 / 16 (1) ++
Регистрация: 20.05.2009
Адрес: Санкт-Петербург
Что-то не помогает..все то же самое... 0x80044150 Generic SQL erro
Старый 02.06.2009, 16:10   #4  
Kipetcoff is offline
Kipetcoff
Участник
 
136 / 16 (1) ++
Регистрация: 20.05.2009
Адрес: Санкт-Петербург
Решил покопаться с помощью 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?
Старый 02.06.2009, 17:23   #5  
Kipetcoff is offline
Kipetcoff
Участник
 
136 / 16 (1) ++
Регистрация: 20.05.2009
Адрес: Санкт-Петербург
В трассировке именно то что я в 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'."
Старый 02.06.2009, 18:15   #6  
Kipetcoff is offline
Kipetcoff
Участник
 
136 / 16 (1) ++
Регистрация: 20.05.2009
Адрес: Санкт-Петербург
Заработало..я поменял код создания сервиса

Код:
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;
Старый 02.06.2009, 18:45   #7  
Kipetcoff is offline
Kipetcoff
Участник
 
136 / 16 (1) ++
Регистрация: 20.05.2009
Адрес: Санкт-Петербург
Почему-то не работает код crmService.Credentials = System.Net.CredentialCache.DefaultCredentials; Хотя в моем приложениие есть

<authentication mode="Windows"/>
<identity impersonate="true"/>
Что такое происходит?
Старый 03.06.2009, 00:33   #8  
a33ik is offline
a33ik
Чайный пьяница
Аватар для a33ik
MCP
MCBMSS
Злыдни
Соотечественники
Most Valuable Professional
Лучший по профессии 2017
Лучший по профессии 2015
Лучший по профессии 2014
Лучший по профессии AXAWARD 2013
Лучший по профессии 2011
Лучший по профессии 2009
 
3,243 / 896 (36) +++++++
Регистрация: 02.07.2008
Адрес: Greenville, SC
Цитата:
Сообщение от Kipetcoff Посмотреть сообщение
Почему-то не работает код crmService.Credentials = System.Net.CredentialCache.DefaultCredentials; Хотя в моем приложениие есть

<authentication mode="Windows"/>
<identity impersonate="true"/>
Что такое происходит?
<authentication mode="Windows"/> это уберите.
Плюс всю работу с CrmService оберните конструкцией using (new CrmImpersonator()){...}
__________________
Эмо разработчик, сначала пишу код, потом плачу над его несовершенством.

Подписывайтесь на мой блог, twitter и YouTube канал.
Пользуйтесь моим Ultimate Workflow Toolkit
Старый 03.06.2009, 10:44   #9  
Kipetcoff is offline
Kipetcoff
Участник
 
136 / 16 (1) ++
Регистрация: 20.05.2009
Адрес: Санкт-Петербург
Спасибо, помогло!!!
Старый 08.06.2009, 11:21   #10  
Kipetcoff is offline
Kipetcoff
Участник
 
136 / 16 (1) ++
Регистрация: 20.05.2009
Адрес: Санкт-Петербург
К сожалению все таки не работает 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;					
				}
			}
		}
		}
	}
Вложения
Тип файла: txt Web.config.txt (6.5 Кб, 296 просмотров)

Последний раз редактировалось Kipetcoff; 08.06.2009 в 12:34.
Старый 08.06.2009, 15:15   #11  
Kipetcoff is offline
Kipetcoff
Участник
 
136 / 16 (1) ++
Регистрация: 20.05.2009
Адрес: Санкт-Петербург
Опытным путем выяснил что причина в конфликте конструкций using (new CrmImpersonator()) и try catch. Нужно использовать или то или другое. Осталось только понять почему так..
 

Похожие темы
Тема Автор Раздел Ответов Посл. сообщение
Новый пользователь из другого домена if_maks Dynamics CRM: Администрирование 27 11.11.2009 14:54
Как лучше реализовать? Создать новый объект или... Sederick Dynamics CRM: Функционал 12 08.04.2009 14:04
Plugin на для обновления задачи (Task) Bondonello Dynamics CRM: Разработка 14 25.02.2009 12:13
связь через новый объект valk Dynamics CRM: Разработка 3 07.12.2007 08:56
связь через новый объект valk Dynamics CRM: Разработка 0 06.12.2007 12:09

Ваши права в разделе
Вы не можете создавать новые темы
Вы не можете отвечать в темах
Вы не можете прикреплять вложения
Вы не можете редактировать свои сообщения

BB коды Вкл.
Смайлы Вкл.
[IMG] код Вкл.
HTML код Выкл.
Быстрый переход

Рейтинг@Mail.ru
Часовой пояс GMT +3, время: 18:42.
Powered by vBulletin® v3.8.5. Перевод: zCarot
Контактная информация, Реклама.