本文整理汇总了C#中OrganizationService.Create方法的典型用法代码示例。如果您正苦于以下问题:C# OrganizationService.Create方法的具体用法?C# OrganizationService.Create怎么用?C# OrganizationService.Create使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类OrganizationService
的用法示例。
在下文中一共展示了OrganizationService.Create方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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); ;
}
}
示例2: AddRemarksForEntry
public void AddRemarksForEntry(Guid entryID, Annotation data, string Username, string Password)
{
Entity note = new Entity("annotation");
note["objectid"] = new EntityReference("gsc_timeentry", entryID);
note["subject"] = data.Subject;
note["notetext"] = data.NoteText;
string Url = ConfigurationManager.AppSettings["Url"].ToString();
string CrmConnectionString = string.Format("Url={0}; Username={1}; Password={2}",
Url, Username, Password);
CrmConnection crmConnection = null;
crmConnection = CrmConnection.Parse(CrmConnectionString);
OrganizationService service = new OrganizationService(crmConnection);
service.Create(note);
}
示例3: Post
public string Post([FromBody] FormDataCollection formValues)
{
string domain = HttpContext.Current.Request.Headers["Origin"].ToLower();
string host = HttpContext.Current.Request.Url.Host.ToLower();
//if (!domain.Contains("jlleadform.azurewebsites.net") && !domain.Contains(host))
// return "fail!";
CrmConnection connection = CrmConnection.Parse(
ConfigurationManager.ConnectionStrings["CRMOnlineO365"].ConnectionString);
using (_orgService = new OrganizationService(connection))
{
Entity lead = new Entity("lead");
lead["firstname"] = formValues.Get("FirstName");
lead["lastname"] = formValues.Get("LastName");
_orgService.Create(lead);
}
return "success";
}
示例4: Process
/// <summary>
/// runs the import process
/// </summary>
public void Process()
{
logger = LogManager.GetLogger(typeof(Importer));
LogMessage("INFO", "starting job");
ParseConnections();
SetupGuidMappings();
LogMessage("INFO","processing records");
OrganizationService sourceService = new OrganizationService(_sourceConn);
OrganizationService targetService = new OrganizationService(_targetConn);
foreach (var item in JobSteps)
{
JobStep step = (JobStep)item;
LogMessage("INFO",string.Format("starting step {0}", step.StepName));
string fetchQuery = step.StepFetch;
LogMessage("INFO"," retrieving records");
// Set the number of records per page to retrieve.
int fetchCount = 5000;
// Initialize the page number.
int pageNumber = 1;
// Specify the current paging cookie. For retrieving the first page,
// pagingCookie should be null.
string pagingCookie = null;
//create a list of entities to hold retrieved entities so we can page through results
List<Entity> ec = new List<Entity>();
while (true)
{
// Build fetchXml string with the placeholders.
string fetchXml = CreateXml(fetchQuery, pagingCookie, pageNumber, fetchCount);
EntityCollection retrieved = sourceService.RetrieveMultiple(new FetchExpression(fetchXml));
ec.AddRange(retrieved.Entities);
if (retrieved.MoreRecords)
{
// Increment the page number to retrieve the next page.
pageNumber++;
// Set the paging cookie to the paging cookie returned from current results.
pagingCookie = retrieved.PagingCookie;
}
else
{
// If no more records in the result nodes, exit the loop.
break;
}
}
LogMessage("INFO",string.Format(" {0} records retrieved", ec.Count));
if (ec.Count > 0)
{
foreach (Entity entity in ec)
{
//create a list to hold the replacement guids. a second pass is required because c# disallows modifying a collection while enumerating
List<KeyValuePair<string, object>> guidsToUpdate = new List<KeyValuePair<string, object>>();
LogMessage("INFO",string.Format(" processing record {0}, {1}", entity.Id, entity.LogicalName));
try
{
LogMessage("INFO"," processing GUID replacements");
foreach (KeyValuePair<string, object> attribute in entity.Attributes)
{
//LogMessage("INFO",string.Format("Attribute - {0} {1}", attribute.Key, attribute.Value.GetType().ToString()));
if (attribute.Value is Microsoft.Xrm.Sdk.EntityReference)
{
//LogMessage("INFO","getting source");
EntityReference source = ((EntityReference)attribute.Value);
try
{
//LogMessage("INFO","looking for GUID replacement");
Guid sourceId = source.Id;
Guid targetId = _mappings.Find(t => t.sourceId == source.Id).targetId;
source.Id = targetId;
guidsToUpdate.Add(new KeyValuePair<string, object>(attribute.Key, source));
//LogMessage("INFO",string.Format("replacement found - {0} -> {1}", sourceId, targetId));
}
catch (System.NullReferenceException ex)
{
//LogMessage("INFO", "NullReferenceException happened");
//do nothing because nullreferenceexception means there's no guid mapping to use
}
}
}
//now actually update the GUIDs with the mapped values
foreach (KeyValuePair<string, object> attribute in guidsToUpdate)
{
//LogMessage("INFO",string.Format(" replacing attribute GUID {0} {1}", attribute.Key, attribute.Value));
entity[attribute.Key] = attribute.Value;
//.........这里部分代码省略.........
示例5: CreateWebResource
private bool CreateWebResource(Guid solutionId, string uniqueName, int type, string prefix, string name, string displayName, string filePath, string relativePath)
{
try
{
CrmConnection connection = CrmConnection.Parse(_connection.ConnectionString);
using (_orgService = new OrganizationService(connection))
{
Entity webResource = new Entity("webresource");
webResource["name"] = prefix + name;
webResource["webresourcetype"] = new OptionSetValue(type);
if (!string.IsNullOrEmpty(displayName))
webResource["displayname"] = displayName;
if (type == 8)
webResource["silverlightversion"] = "4.0";
string extension = Path.GetExtension(filePath);
List<string> imageExs = new List<string>() { ".ICO", ".PNG", ".GIF", ".JPG" };
string content;
//TypeScript
if (extension != null && (extension.ToUpper() == ".TS"))
{
content = File.ReadAllText(Path.ChangeExtension(filePath, ".js"));
webResource["content"] = EncodeString(content);
}
//Images
else if (extension != null && imageExs.Any(s => extension.ToUpper().EndsWith(s)))
{
content = EncodedImage(filePath, extension);
webResource["content"] = content;
}
//Everything else
else
{
content = File.ReadAllText(filePath);
webResource["content"] = EncodeString(content);
}
Guid id = _orgService.Create(webResource);
_logger.WriteToOutputWindow("New Web Resource Created: " + id, Logger.MessageType.Info);
//Add to the choosen solution (not default)
if (solutionId != new Guid("FD140AAF-4DF4-11DD-BD17-0019B9312238"))
{
AddSolutionComponentRequest scRequest = new AddSolutionComponentRequest
{
ComponentType = 61,
SolutionUniqueName = uniqueName,
ComponentId = id
};
AddSolutionComponentResponse response =
(AddSolutionComponentResponse)_orgService.Execute(scRequest);
_logger.WriteToOutputWindow("New Web Resource Added To Solution: " + response.id, Logger.MessageType.Info);
}
NewId = id;
NewType = type;
NewName = prefix + name;
if (!string.IsNullOrEmpty(displayName))
NewDisplayName = displayName;
NewBoundFile = relativePath;
NewSolutionId = solutionId;
return true;
}
}
catch (FaultException<OrganizationServiceFault> crmEx)
{
_logger.WriteToOutputWindow("Error Creating Web Resource: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error);
return false;
}
catch (Exception ex)
{
_logger.WriteToOutputWindow("Error Creating Web Resource: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error);
return false;
}
}
示例6: 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);
}
}
示例7: Run
/// <summary>
/// The Run() method first connects to the organization service. Afterwards,
/// basic create, retrieve, update, and delete entity operations are performed.
/// </summary>
/// <param name="connectionString">Provides service connection information.</param>
/// <param name="promptforDelete">When True, the user will be prompted to delete all
/// created entities.</param>
public void Run(String connectionString, bool promptforDelete)
{
try
{
// Establish a connection to the organization web service.
Print("Connecting to the server ...");
Microsoft.Xrm.Client.CrmConnection connection = CrmConnection.Parse(connectionString);
// Obtain an organization service proxy.
// The using statement assures that the service proxy will be properly disposed.
using (_orgService = new OrganizationService(connection))
{
Print("connected");
Print("Authenticating the user ...");
// Create any entity records this sample requires.
CreateRequiredRecords();
// Obtain information about the logged on user from the web service.
Guid userid = ((WhoAmIResponse)_orgService.Execute(new WhoAmIRequest())).UserId;
SystemUser systemUser = (SystemUser)_orgService.Retrieve("systemuser", userid,
new ColumnSet(new string[] { "firstname", "lastname" }));
Println("Logged on user is " + systemUser.FirstName + " " + systemUser.LastName + ".");
// Retrieve the version of Microsoft Dynamics CRM.
RetrieveVersionRequest versionRequest = new RetrieveVersionRequest();
RetrieveVersionResponse versionResponse =
(RetrieveVersionResponse)_orgService.Execute(versionRequest);
Println("Microsoft Dynamics CRM version " + versionResponse.Version + ".");
// Instantiate an account object. Note the use of option set enumerations defined in OptionSets.cs.
// Refer to the Entity Metadata topic in the SDK documentation to determine which attributes must
// be set for each entity.
Account account = new Account { Name = "Fourth Coffee" };
account.AccountCategoryCode = new OptionSetValue((int)AccountAccountCategoryCode.PreferredCustomer);
account.CustomerTypeCode = new OptionSetValue((int)AccountCustomerTypeCode.Investor);
// Create an account record named Fourth Coffee.
_accountId = _orgService.Create(account);
Println(account.LogicalName + " " + account.Name + " created, ");
// Retrieve several attributes from the new account.
ColumnSet cols = new ColumnSet(
new String[] { "name", "address1_postalcode", "lastusedincampaign" });
Account retrievedAccount = (Account)_orgService.Retrieve("account", _accountId, cols);
Print("retrieved, ");
// Update the postal code attribute.
retrievedAccount.Address1_PostalCode = "98052";
// The address 2 postal code was set accidentally, so set it to null.
retrievedAccount.Address2_PostalCode = null;
// Shows use of a Money value.
retrievedAccount.Revenue = new Money(5000000);
// Shows use of a Boolean value.
retrievedAccount.CreditOnHold = false;
// Update the account record.
_orgService.Update(retrievedAccount);
Print("and updated.");
// Delete any entity records this sample created.
DeleteRequiredRecords(promptforDelete);
}
}
// Catch any service fault exceptions that Microsoft Dynamics CRM throws.
catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
{
// You can handle an exception here or pass it back to the calling method.
throw;
}
}
示例8: Main
static void Main(string[] args)
{
Console.WriteLine("Enter the source connection string: ");
sourceOrg = Console.ReadLine();
try
{
sourceConn = CrmConnection.Parse(sourceOrg);
}
catch(Exception ex)
{
Console.WriteLine("Could not parse source connection string: {0}", ex.Message);
return;
}
Console.WriteLine("Enter the destination connection string: ");
targetOrg = Console.ReadLine();
try
{
targetConn = CrmConnection.Parse(targetOrg);
}
catch (Exception ex)
{
Console.WriteLine("Could not parse destination connection string: {0}", ex.Message);
return;
}
//export teamtemplates
using (OrganizationService service = new OrganizationService(sourceConn))
{
try
{
//attributes to exclude from the query
List<string> IgnoredAttributes = new List<string> { "issystem" };
Console.WriteLine("Retrieving entity metadata . . .");
RetrieveEntityRequest entityreq = new RetrieveEntityRequest
{
LogicalName = "teamtemplate",
EntityFilters = Microsoft.Xrm.Sdk.Metadata.EntityFilters.Attributes
};
RetrieveEntityResponse entityres = (RetrieveEntityResponse)service.Execute(entityreq);
string fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>";
fetchXml += "<entity name='teamtemplate'>";
foreach (AttributeMetadata amd in entityres.EntityMetadata.Attributes)
{
if (!IgnoredAttributes.Contains(amd.LogicalName))
{
fetchXml += "<attribute name='" + amd.LogicalName + "' />";
//Console.WriteLine(amd.LogicalName);
}
}
fetchXml += "</entity></fetch>";
Console.WriteLine("");
Console.WriteLine("Exporting data . . .");
exported = service.RetrieveMultiple(new FetchExpression(fetchXml));
}
catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
{
Console.WriteLine("Could not export data: {0}", ex.Message);
return;
}
}
//import teamtemplates
Console.WriteLine("Importing data . . .");
using (OrganizationService service = new OrganizationService(targetConn))
{
if (exported.Entities.Count > 0)
{
foreach (Entity entity in exported.Entities)
{
try
{
//Console.WriteLine("Id - {0}", entity.Id.ToString());
//try to update first
try
{
service.Update(entity);
}
catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
{
//if update fails, then create
service.Create(entity);
}
}
catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
{
//if everything fails, return error
Console.WriteLine("Error: {0} - {1}", entity.Id, entity["teamtemplatename"]);
}
}
}
}
Console.WriteLine("Import complete");
Console.WriteLine("");
Console.WriteLine("Press the enter key to exit");
Console.ReadLine();
//.........这里部分代码省略.........
示例9: SetAnnotationToSprava
private static void SetAnnotationToSprava()
{
var service = new OrganizationService(connection);
var dataFromXmlx = new Program().ExcelOpenSpreadsheets(@"C:\Users\savchinvv\Desktop\Примечания.xlsx");
for (int i = 2; i < dataFromXmlx.Tables[0].Rows.Count; i++)
{
if (!string.IsNullOrWhiteSpace(dataFromXmlx.Tables[0].Rows[i][0].ToString()))
{
var sprava = ToSpravaEntity(dataFromXmlx.Tables[0].Rows[i][1].ToString());
if (sprava != null)
{
var createAnn = new Annotation()
{
NoteText = dataFromXmlx.Tables[0].Rows[i][0].ToString(),
ObjectId = sprava,
ObjectTypeCode = new_spravastr.EntityLogicalName
};
service.Create(createAnn);
Console.WriteLine("{0} - добавлен Анотатион", dataFromXmlx.Tables[0].Rows[i][1].ToString());
}
}
}
}
示例10: Create
public void Create(string entityName, [FromBody] JObject objStructure)
{
var connectionString = ConfigurationManager.ConnectionStrings["CRMConnectionString"].ConnectionString;
CrmConnection crmConnection = CrmConnection.Parse(connectionString);
using (OrganizationService service = new OrganizationService(crmConnection))
{
if (objStructure != null)
{
Entity entity = new Entity(entityName);
Guid guidValue;
foreach (var attribute in objStructure)
{
if (Guid.TryParse(attribute.Value.ToString(), out guidValue))
{
RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest
{
EntityLogicalName = entityName,
LogicalName = attribute.Key.ToString(),
RetrieveAsIfPublished = true
};
// Execute the request
RetrieveAttributeResponse attributeResponse =
(RetrieveAttributeResponse)service.Execute(attributeRequest);
if (attributeResponse.AttributeMetadata.AttributeType == AttributeTypeCode.Lookup)
{
string relatedEntityName =
((LookupAttributeMetadata)(attributeResponse.AttributeMetadata)).Targets[0];
EntityReference eref = new EntityReference(relatedEntityName, guidValue);
entity[attribute.Key.ToString()] = eref;
continue;
}
}
entity[attribute.Key.ToString()] = attribute.Value.ToString();
}
service.Create(entity);
}
}
}
示例11: Main
public static void Main()
{
//get the config data
GetConfig();
//connect to rabbitmq
Console.WriteLine("Connecting . . .");
var factory = new ConnectionFactory();
factory.HostName = _brokerEndpoint;
factory.UserName = _brokerUser;
factory.Password = _brokerPassword;
factory.VirtualHost = "/"; //assumes we use the default vhost
factory.Protocol = Protocols.DefaultProtocol; //assumes we use the default protocol
factory.Port = AmqpTcpEndpoint.UseDefaultPort; //assumes we use the default port
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
//wait for some messages
var consumer = new QueueingBasicConsumer(channel);
channel.BasicConsume(_queue, false, consumer);
Console.WriteLine(" [*] Waiting for messages. To exit press CTRL+C");
//instantiate crm org service
using (OrganizationService service = new OrganizationService(_targetConn))
{
while (true)
{
//get the message from the queue
var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
try
{
//deserialize message json to object
LeadType lead = JsonConvert.DeserializeObject<LeadType>(message);
try
{
//create record in crm
Entity entity = new Entity("lead");
entity["firstname"] = lead.FirstName;
entity["lastname"] = lead.LastName;
entity["subject"] = lead.Topic;
entity["companyname"] = lead.Company;
service.Create(entity);
//write success message to cli
Console.WriteLine("Created lead: {0} {1}", lead.FirstName, lead.LastName);
//IMPORTANT - tell the queue the message was processed successfully so it doesn't get requeued
channel.BasicAck(ea.DeliveryTag, false);
}
catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
{
//return error - note no confirmation is sent to the queue, so the message will be requeued
Console.WriteLine("Could not create lead: {0} {1}", lead.FirstName, lead.LastName);
Console.WriteLine("Error: {0}", ex.Message);
}
}
catch(Exception ex)
{
//return error - note no confirmation is sent to the queue, so the message will be requeued
Console.WriteLine("Could not process message from queue");
Console.WriteLine("Error: {0}", ex.Message);
}
}
}
}
}
}
示例12: GetUniqueID
private Guid GetUniqueID(string username, bool isAuthenticated, bool ignoreAuthenticationType)
{
if (username == null)
throw new ArgumentNullException("User name cannot be null.");
using (OrganizationService service = new OrganizationService(OurConnect()))
{
ConditionExpression usernameCondition = new ConditionExpression();
ConditionExpression appCondition = new ConditionExpression();
usernameCondition.AttributeName = consts.username;
usernameCondition.Operator = ConditionOperator.Equal;
usernameCondition.Values.Add(username);
appCondition.AttributeName = consts.appname;
appCondition.Operator = ConditionOperator.Equal;
appCondition.Values.Add(_ApplicationName);
FilterExpression filter = new FilterExpression();
filter.Conditions.Add(usernameCondition);
filter.Conditions.Add(appCondition);
if (!ignoreAuthenticationType)
{
ConditionExpression isanonymousCondition = new ConditionExpression();
isanonymousCondition.AttributeName = consts.isanonymous;
isanonymousCondition.Operator = ConditionOperator.Equal;
isanonymousCondition.Values.Add(!isAuthenticated);
filter.Conditions.Add(isanonymousCondition);
}
QueryExpression query = new QueryExpression(consts.userprofile);
query.ColumnSet.AddColumn(consts.profileid);
query.Criteria.AddFilter(filter);
EntityCollection collection = service.RetrieveMultiple(query);
Guid uniqueID;
if (collection.Entities.Count != 0)
uniqueID = (Guid)collection.Entities[0][consts.profileid];
else
{
Entity newProfile = new Entity(consts.userprofile);
newProfile[consts.username] = username;
newProfile[consts.appname] = _ApplicationName;
newProfile[consts.isanonymous] = !isAuthenticated;
uniqueID = (Guid)service.Create(newProfile);
activity(username, "Profile Created", true);
}
return uniqueID;
}
}
示例13: activity
/*ACTIVITIES*/
protected void activity(string username, string message, bool isUpdate)
{
using (OrganizationService service = new OrganizationService(OurConnect()))
{
Entity newActivity = new Entity(consts.activities);
newActivity[consts.activitytime] = DateTime.Now;
newActivity[consts.activityid] = Guid.NewGuid();
newActivity[consts.to] = username;
newActivity[consts.from] = _ApplicationName;
newActivity[consts.subject] = message;
if (message != "")
service.Create(newActivity);
if (isUpdate)
{
newActivity[consts.subject] = "Modified";
service.Create(newActivity);
}
return;
}
}
示例14: CreateUser
//Takes as input a username, password, email, password question and answer of type string; a boolean value for approval, a provider user key object, and a status variable of type Membership Create Status
//Returns a Membership user after creating a new user account in CRM with the specified input (userame, password, email, password question and answer)
public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
{
using (OrganizationService service = new OrganizationService(OurConnect()))
{
ConditionExpression usernameCondition = new ConditionExpression();
ConditionExpression appCondition = new ConditionExpression();
usernameCondition.AttributeName = consts.username;
usernameCondition.Operator = ConditionOperator.Equal;
usernameCondition.Values.Add(username);
appCondition.AttributeName = consts.appname;
appCondition.Operator = ConditionOperator.Equal;
appCondition.Values.Add(_ApplicationName);
FilterExpression filter = new FilterExpression();
filter.Conditions.Add(usernameCondition);
QueryExpression query = new QueryExpression(consts.useraccount);
query.Criteria.AddFilter(filter); //query CRM with the new filter for username
EntityCollection collection = service.RetrieveMultiple(query); //retrieve all records with same username
if (collection.Entities.Count != 0)
{
status = MembershipCreateStatus.DuplicateUserName;
return null;
}
else
{
if (_RequiresQuestionAndAnswer)
{
if (passwordAnswer == null)
{
status = MembershipCreateStatus.InvalidAnswer;
return null;
}
if (passwordQuestion == null)
{
status = MembershipCreateStatus.InvalidQuestion;
return null;
}
}
if (_RequireUniqueEmail && GetUserNameByEmail(email) != null)
{
status = MembershipCreateStatus.DuplicateEmail;
return null;
}
else
{
if (providerUserKey == null)
{
providerUserKey = Guid.NewGuid();
}
else
{
if (!(providerUserKey is Guid))
{
status = MembershipCreateStatus.InvalidProviderUserKey;
return null;
}
}
Entity newMember = new Entity(consts.useraccount);
newMember[consts.accountid] = providerUserKey;
newMember[consts.name] = "";
newMember[consts.username] = username;
newMember[consts.password] = password;
newMember[consts.email] = email;
newMember[consts.securityquestion] = passwordQuestion;
newMember[consts.securityanswer] = passwordAnswer;
newMember[consts.appname] = _ApplicationName;
newMember[consts.deleteduser] = false;
newMember[consts.lockn] = false;
newMember[consts.online] = true;
newMember[consts.loginattempts] = 0;
Guid _accountID = service.Create(newMember);
status = MembershipCreateStatus.Success;
activity(username, "Created On", false);
return GetUser(username);
}
}
}
}
示例15: OrganizationService
// < ----- )))))))))))))))))))))))))
private static void СозданиеЗадач()
{
var service = new OrganizationService(connection);
var dataFromXmlx = new Program().ExcelOpenSpreadsheets(@"C:\Users\savchinvv\Desktop\Задачи.xlsx");
for (int i = 2; i < dataFromXmlx.Tables[0].Rows.Count; i++)
{
var newTask = new SoftLine.Models.Task()
{
Subject = dataFromXmlx.Tables[0].Rows[i][0].ToString(),
RegardingObjectId = ToSpravaEntity(dataFromXmlx.Tables[0].Rows[i][1].ToString()),
PriorityCode = ToOptionSetValue(dataFromXmlx.Tables[0].Rows[i][2].ToString()),
ScheduledEnd = FindDate(dataFromXmlx.Tables[0].Rows[i][3].ToString()),
ScheduledStart = FindDate(dataFromXmlx.Tables[0].Rows[i][4].ToString()),
ActualDurationMinutes = ToInt32(dataFromXmlx.Tables[0].Rows[i][5].ToString()),
Description = dataFromXmlx.Tables[0].Rows[i][6].ToString(),
PercentComplete = ToInt32(dataFromXmlx.Tables[0].Rows[i][7].ToString()),
ActualStart = FindDate(dataFromXmlx.Tables[0].Rows[i][9].ToString()),
ActualEnd = FindDate(dataFromXmlx.Tables[0].Rows[i][10].ToString())
};
var id = service.Create(newTask);
Console.WriteLine("{0} - созданая Задача", dataFromXmlx.Tables[0].Rows[i][0].ToString());
bool? status = false;
if (dataFromXmlx.Tables[0].Rows[i][8].ToString() == "Завершено")
{
status = ChangeStateCode(id);
}
Console.WriteLine("Задача = StatusChange->{0}", status ?? null);
}
}