static void Main(string[] args)
        {
            CrmServiceClient crmSvc = new CrmServiceClient("yourUserId", CrmServiceClient.MakeSecureString("yourPassword"), "NorthAmerica", "UniqueOrgName", isOffice365: true);

            using (OrganizationServiceProxy proxy = crmSvc.OrganizationServiceProxy)
            {
                EntityCollection organizationSettings;
                bool IsSOPIntegrationEnabled;
                QueryForSOPSetting(proxy, out organizationSettings, out IsSOPIntegrationEnabled);

                Console.WriteLine(string.Format("IsSOPIntegrationEnabled: {0}", IsSOPIntegrationEnabled.ToString()));

                if (IsSOPIntegrationEnabled)
                    IsSOPIntegrationEnabled = false;

                Entity org = new Entity("organization");
                org.Id = organizationSettings.Entities[0].Id;
                org["issopintegrationenabled"] = false;

                proxy.Update(org);

                Console.WriteLine(string.Format("IsSOPIntegrationEnabled: {0}", IsSOPIntegrationEnabled.ToString()));

            }
        }
Esempio n. 2
0
        protected IOrganizationService ConnectToCrm()
        {
            //TraceControlSettings.TraceLevel = System.Diagnostics.SourceLevels.All;
            //TraceControlSettings.AddTraceListener(new TextWriterTraceListener("XrmTooling.txt"));

            WriteDebug("Instantiating connection...");
            var connector = new CrmServiceClient(ConnectionString);

            if (!connector.IsReady)
            {
                WriteDebug("Could not connect to CRM.");
                throw new Exception(connector.LastCrmError);
            }
            else
            {
                WriteDebug("Connected to " + connector.ConnectedOrgFriendlyName);
            }

            var service = connector.OrganizationServiceProxy;

            return service;
        }
Esempio n. 3
0
        [STAThread] // Required to support the interactive login experience
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");

                if (service.IsReady)
                {
                    // Create any entity records that the demonstration code requires
                    SetUpSample(service);

                    #region Demonstrate

                    #region Send request

                    // Create an ExecuteWorkflow request.
                    ExecuteWorkflowRequest request = new ExecuteWorkflowRequest()
                    {
                        WorkflowId = _workflowId,
                        EntityId   = _leadId
                    };
                    Console.Write("Created an ExecuteWorkflow request, ");

                    // Execute the workflow.
                    ExecuteWorkflowResponse response =
                        (ExecuteWorkflowResponse)service.Execute(request);
                    Console.WriteLine("and sent the request to service.");

                    #endregion Send request

                    #region Check success

                    ColumnSet        cols            = new ColumnSet("statecode");
                    QueryByAttribute retrieveOpQuery = new QueryByAttribute();
                    retrieveOpQuery.EntityName = AsyncOperation.EntityLogicalName;
                    retrieveOpQuery.ColumnSet  = cols;
                    retrieveOpQuery.AddAttributeValue("asyncoperationid", response.Id);

                    // Wait for the asyncoperation to complete.
                    // (wait no longer than 1 minute)
                    for (int i = 0; i < 60; i++)
                    {
                        System.Threading.Thread.Sleep(1000);

                        EntityCollection retrieveOpResults =
                            service.RetrieveMultiple(retrieveOpQuery);

                        if (retrieveOpResults.Entities.Count() > 0)
                        {
                            AsyncOperation op =
                                (AsyncOperation)retrieveOpResults.Entities[0];
                            if (op.StateCode == AsyncOperationState.Completed)
                            {
                                _asyncOperationId = op.AsyncOperationId.Value;
                                Console.WriteLine("AsyncOperation completed successfully.");
                                break;
                            }
                        }

                        if (i == 59)
                        {
                            throw new TimeoutException("AsyncOperation failed to complete in under one minute.");
                        }
                    }

                    // Retrieve the task that was created by the workflow.
                    cols = new ColumnSet("activityid");
                    QueryByAttribute retrieveActivityQuery = new QueryByAttribute();
                    retrieveActivityQuery.EntityName = PhoneCall.EntityLogicalName;
                    retrieveActivityQuery.ColumnSet  = cols;
                    retrieveActivityQuery.AddAttributeValue("subject", "First call to Diogo Andrade");

                    EntityCollection results =
                        service.RetrieveMultiple(retrieveActivityQuery);

                    if (results.Entities.Count() == 0)
                    {
                        throw new InvalidOperationException("Phone call activity was not successfully created.");
                    }
                    else
                    {
                        Console.WriteLine("Phone call activity '{0}' successfully created from the workflow.",
                                          "First call to Diogo Andrade");
                    }

                    #endregion Check success

                    #endregion Demonstrate

                    CleanUpSample(service);
                }
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
        [STAThread] // Added to support UX
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    #region Sample Code
                    //////////////////////////////////////////////
                    #region Set up
                    SetUpSample(service);
                    #endregion Set up
                    #region Demonstrate

                    //Read the descriptive data from the XML file
                    XDocument xmlDoc = XDocument.Load("../../ImportJob.xml");

                    //Create a collection of anonymous type references to each of the Web Resources
                    var webResources = from webResource in xmlDoc.Descendants("webResource")
                                       select new
                    {
                        path        = webResource.Element("path").Value,
                        displayName = webResource.Element("displayName").Value,
                        description = webResource.Element("description").Value,
                        name        = webResource.Element("name").Value,
                        type        = webResource.Element("type").Value
                    };

                    // Loop through the collection creating Web Resources
                    int counter = 0;
                    foreach (var webResource in webResources)
                    {
                        //<snippetImportWebResources2>
                        //Set the Web Resource properties
                        WebResource wr = new WebResource
                        {
                            Content         = getEncodedFileContents(@"../../" + webResource.path),
                            DisplayName     = webResource.displayName,
                            Description     = webResource.description,
                            Name            = _customizationPrefix + webResource.name,
                            LogicalName     = WebResource.EntityLogicalName,
                            WebResourceType = new OptionSetValue(Int32.Parse(webResource.type))
                        };

                        // Using CreateRequest because we want to add an optional parameter
                        var cr = new CreateRequest
                        {
                            Target = wr
                        };
                        //Set the SolutionUniqueName optional parameter so the Web Resources will be
                        // created in the context of a specific solution.
                        cr.Parameters.Add("SolutionUniqueName", _ImportWebResourcesSolutionUniqueName);

                        CreateResponse cresp = (CreateResponse)service.Execute(cr);
                        //</snippetImportWebResources2>
                        // Capture the id values for the Web Resources so the sample can delete them.
                        _webResourceIds[counter] = cresp.id;
                        counter++;
                        Console.WriteLine("Created Web Resource: {0}", webResource.displayName);
                    }

                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                #endregion Demonstrate
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Dynamics CRM";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            #endregion Sample Code
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Esempio n. 5
0
        public CrmServiceClient GetCrmServiceClient(bool forceNewService = false)
        {
            if (forceNewService == false && crmSvc != null)
            {
                return crmSvc;
            }

            //return new CrmServiceClient(GetOrganizationCrmConnectionString());

            if (UseOnline)
            {
                var tasks = new List<Task<CrmServiceClient>>
                {
                    Task<CrmServiceClient>.Factory.StartNew(() => ConnectOnline(UseOsdp, true)),
                    Task<CrmServiceClient>.Factory.StartNew(() => ConnectOnline(UseOsdp, false))
                };

                tasks[0].Wait();
                tasks[1].Wait();

                crmSvc = tasks.FirstOrDefault(t => t.Result.IsReady)?.Result;

                // crmSvc = ConnectOnline(UseOsdp);

                AuthType = AuthenticationProviderType.OnlineFederation;
            }
            else if (UseIfd)
            {
                var password = CryptoManager.Decrypt(userPassword, ConnectionManager.CryptoPassPhrase,
                   ConnectionManager.CryptoSaltValue,
                   ConnectionManager.CryptoHashAlgorythm,
                   ConnectionManager.CryptoPasswordIterations,
                   ConnectionManager.CryptoInitVector,
                   ConnectionManager.CryptoKeySize);

                crmSvc = new CrmServiceClient(UserName, CrmServiceClient.MakeSecureString(password), UserDomain, HomeRealmUrl,
                    ServerName, ServerPort.ToString(), OrganizationUrlName, true, UseSsl);

                AuthType = AuthenticationProviderType.Federation;
            }
            else
            {
                NetworkCredential credential;
                if (!IsCustomAuth)
                {
                    credential = CredentialCache.DefaultNetworkCredentials;
                }
                else
                {
                    var password = CryptoManager.Decrypt(userPassword, ConnectionManager.CryptoPassPhrase,
                  ConnectionManager.CryptoSaltValue,
                  ConnectionManager.CryptoHashAlgorythm,
                  ConnectionManager.CryptoPasswordIterations,
                  ConnectionManager.CryptoInitVector,
                  ConnectionManager.CryptoKeySize);

                    credential = new NetworkCredential(UserName, password, UserDomain);
                }
                crmSvc = new CrmServiceClient(credential, AuthenticationType.AD, ServerName, ServerPort.ToString(), OrganizationUrlName, true, UseSsl);

                AuthType = AuthenticationProviderType.ActiveDirectory;
            }

            if (!crmSvc.IsReady)
            {
                var error = crmSvc.LastCrmError;
                crmSvc = null;
                throw new Exception(error);
            }

            return crmSvc;
        }
Esempio n. 6
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            // TODO Create entity records

            Console.WriteLine("Required records have been created.");
        }
Esempio n. 7
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Creates the email activity.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            // TODO Create entity records
            #region Create or Retrieve the necessary system users

            // Retrieve a sales manager.
            _salesManagerId =
                SystemUserProvider.RetrieveMarketingManager(serviceProxy: _serviceProxy);

            #endregion

            #region Create PhoneCall record and supporting account

            Account newAccount = new Account
            {
                Name = "Margie's Travel",
                Address1_PostalCode = "99999"
            };
            _accountId    = (_serviceProxy.Create(newAccount));
            newAccount.Id = _accountId;

            // Create Guids for PhoneCalls
            _phoneCallId  = Guid.NewGuid();
            _phoneCall2Id = Guid.NewGuid();

            // Create ActivityPartys for the phone calls' "From" field.
            ActivityParty activityParty = new ActivityParty()
            {
                PartyId    = newAccount.ToEntityReference(),
                ActivityId = new EntityReference
                {
                    Id          = _phoneCallId,
                    LogicalName = PhoneCall.EntityLogicalName,
                },
                ParticipationTypeMask = new OptionSetValue(9)
            };

            ActivityParty activityPartyClosed = new ActivityParty()
            {
                PartyId    = newAccount.ToEntityReference(),
                ActivityId = new EntityReference
                {
                    Id          = _phoneCall2Id,
                    LogicalName = PhoneCall.EntityLogicalName,
                },
                ParticipationTypeMask = new OptionSetValue(9)
            };

            // Create an open phone call.
            PhoneCall phoneCall = new PhoneCall()
            {
                Id            = _phoneCallId,
                Subject       = "Sample Phone Call",
                DirectionCode = false,
                To            = new ActivityParty[] { activityParty }
            };
            _serviceProxy.Create(phoneCall);

            // Create a second phone call to close
            phoneCall = new PhoneCall()
            {
                Id            = _phoneCall2Id,
                Subject       = "Sample Phone Call 2",
                DirectionCode = false,
                To            = new ActivityParty[] { activityParty },
                ActualEnd     = DateTime.Now
            };
            _serviceProxy.Create(phoneCall);

            // Close the second phone call.
            SetStateRequest closePhoneCall = new SetStateRequest()
            {
                EntityMoniker = phoneCall.ToEntityReference(),
                State         = new OptionSetValue(1),
                Status        = new OptionSetValue(4)
            };
            _serviceProxy.Execute(closePhoneCall);
            Console.WriteLine("Required records have been created.");
            #endregion
        }
Esempio n. 8
0
 public Dynamics365DataAccessLayer_Reused(string connectionString)
 {
     _crmSvc = new CrmServiceClient(connectionString);
 }
Esempio n. 9
0
 public ParallelOrganizationOperationContext(CrmServiceClient proxy)
     : base(proxy)
 {
 }
Esempio n. 10
0
        private void Connect()
        {
            visitedPath.Add(pnlWaiting.Name);

            var settings = new ConnectionSettings
            {
                Domain = txtDomain.Text,
                Username = txtUsername.Text,
                Password = txtPassword.Text,
            };

            if (settings.Password == "@@PASSWORD@@")
            {
            }

            var bw = new BackgroundWorker();
            bw.DoWork += (bwSender, evt) =>
            {
                var bwSettings = (ConnectionSettings)evt.Argument;
                CrmServiceClient crmSvc;

                if (isOnline)
                {
                    Task<CrmServiceClient>[] taskArray =
                {
                    Task<CrmServiceClient>.Factory.StartNew(() => ConnectOnline(true, bwSettings)),
                    Task<CrmServiceClient>.Factory.StartNew(() => ConnectOnline(false, bwSettings)),
                };

                    taskArray[0].Wait();
                    taskArray[1].Wait();

                    var goodResult = taskArray.FirstOrDefault(t => t.Result.IsReady);
                    if (goodResult != null)
                    {
                        crmSvc = goodResult.Result;

                        isOffice365 = taskArray[0].Result.IsReady;
                    }
                    else
                    {
                        crmSvc = taskArray.First().Result;
                    }
                }
                else if (isIfd)
                {
                    crmSvc = new CrmServiceClient(
                       new NetworkCredential(bwSettings.Username, bwSettings.Password, bwSettings.Domain), AuthenticationType.IFD, hostName, hostPort,
                       orga, true, useSsl);
                }
                else
                {
                    if (orga == null)
                    {
                        MessageBox.Show(this, Resources.ConnectionWizard_UnableToDetermineOrganizationFromUrl, Resources.ConnectionWizard_WarningTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);

                        return;
                    }

                    NetworkCredential credential;
                    if (chkUseIntegratedAuthentication.Checked)
                    {
                        credential = CredentialCache.DefaultNetworkCredentials;
                    }
                    else
                    {
                        credential = new NetworkCredential(bwSettings.Username, bwSettings.Password, bwSettings.Domain);
                    }
                    crmSvc = new CrmServiceClient(credential, AuthenticationType.AD, hostName, hostPort, orga, true, useSsl);
                }

                evt.Result = crmSvc;
            };
            bw.RunWorkerCompleted += (bwSender, evt) =>
            {
                if (evt.Error != null)
                {
                    lblDescription.Text = Resources.ConnectionWizard_ErrorHeaderDescription;

                    lblError.Text = evt.Error.Message;
                    DisplayPanel(pnlError);

                    return;
                }

                CrmServiceClient crmSvc = (CrmServiceClient)evt.Result;

                if (!string.IsNullOrEmpty(crmSvc.LastCrmError))
                {
                    lblDescription.Text = Resources.ConnectionWizard_ErrorHeaderDescription;

                    lblError.Text = crmSvc.LastCrmError;
                    DisplayPanel(pnlError);

                    return;
                }

                lblDescription.Text = Resources.ConnectionWizard_SuccessHeaderDescription;

                DisplayPanel(pnlConnected);
                txtConnectionName.Focus();

                serviceClient = crmSvc;
            };
            bw.RunWorkerAsync(settings);
        }
Esempio n. 11
0
        [STAThread] // Added to support UX
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    #region Sample Code
                    ///////////////////////////////////
                    #region Set up
                    SetUpSample(service);
                    #endregion Set up
                    #region Demonstrate

                    // Assign the account to a team.
                    var assignRequest = new AssignRequest()
                    {
                        Assignee = new EntityReference
                        {
                            LogicalName = Team.EntityLogicalName,
                            Id          = _teamId
                        },

                        Target = new EntityReference(Account.EntityLogicalName, _accountId)
                    };

                    service.Execute(assignRequest);

                    Console.WriteLine("The account is owned by the team.");
                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                #endregion Demonstrate
                #endregion Sample Code
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Microsoft Dataverse";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Esempio n. 12
0
        [STAThread] // Added to support UX
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    #region Sample Code
                    ////////////////////////////////////////////
                    #region Set up
                    SetUpSample(service);
                    #endregion Set up
                    #region Demonstrate
                    // Retrieve an account.
                    var account = service.Retrieve("account", accountId, new ColumnSet("name", "creditlimit"));
                    Console.WriteLine("\tThe row version of the created account is {0}", account.RowVersion);

                    if (account != null)
                    {
                        // Create an in-memory account object from the retrieved account.
                        var updatedAccount = new Entity()
                        {
                            LogicalName = account.LogicalName,
                            Id          = account.Id,
                            RowVersion  = account.RowVersion
                        };

                        // Update just the credit limit.
                        updatedAccount["creditlimit"] = new Money(1000000);

                        // Set the request's concurrency behavour to check for a row version match.
                        var accountUpdate = new UpdateRequest()
                        {
                            Target = updatedAccount,
                            ConcurrencyBehavior = ConcurrencyBehavior.IfRowVersionMatches
                        };

                        // Do the update.
                        UpdateResponse accountUpdateResponse = (UpdateResponse)service.Execute(accountUpdate);
                        Console.WriteLine("Account '{0}' updated with a credit limit of {1}.", account["name"],
                                          ((Money)updatedAccount["creditlimit"]).Value);

                        account = service.Retrieve("account", updatedAccount.Id, new ColumnSet());
                        Console.WriteLine("\tThe row version of the updated account is {0}", account.RowVersion);
                        accountRowVersion = account.RowVersion;
                    }

                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }

                #endregion Demonstrate
                #endregion Sample Code
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Microsoft Dataverse";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Button to login to CRM and create a CrmService Client
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoginButton_Click(object sender, RoutedEventArgs e)
        {
            #region Login Control
            // Wire Event to login response.
            ctrl.ConnectionToCrmCompleted += ctrl_ConnectionToCrmCompleted;
            // Show the dialog.
            ctrl.ShowDialog();

            // Handel return.
            if (ctrl.CrmConnectionMgr != null && ctrl.CrmConnectionMgr.CrmSvc != null && ctrl.CrmConnectionMgr.CrmSvc.IsReady)
            {
                //MessageBox.Show("Good Connect");
                LBL_Status.Content = "Connected to CRM";
            }
            else
            {
                LBL_Status.Content = "Connection to CRM Failed";
            }
            //MessageBox.Show("BadConnect");

            #endregion

            #region CRMServiceClient
            if (ctrl.CrmConnectionMgr != null && ctrl.CrmConnectionMgr.CrmSvc != null && ctrl.CrmConnectionMgr.CrmSvc.IsReady)
            {
                CrmServiceClient svcClient = ctrl.CrmConnectionMgr.CrmSvc;
                if (svcClient.IsReady)
                {
                    List <EntityMetadata> entitiesList = svcClient.GetAllEntityMetadata();
                    List <string>         MyEntities   = new List <string>();
                    foreach (EntityMetadata entityinlist in entitiesList)
                    {
                        if (entityinlist.IsCustomizable.Value)
                        {
                            MyEntities.Add(entityinlist.LogicalName);
                            //CB_Entities.Items.Add(entityinlist.LogicalName);
                        }
                    }
                    MyEntities.Sort();
                    foreach (string item in MyEntities)
                    {
                        CB_Entities.Items.Add(item);
                    }

                    //                    // Get data from CRM .
                    //                    string FetchXML =
                    //                        @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                    //                        <entity name='account'>
                    //                            <attribute name='name' />
                    //                            <attribute name='primarycontactid' />
                    //                            <attribute name='telephone1' />
                    //                            <attribute name='accountid' />
                    //                            <order attribute='name' descending='false' />
                    //                          </entity>
                    //                        </fetch>";

                    //                    var Result = svcClient.GetEntityDataByFetchSearchEC(FetchXML);
                    //                    if (Result != null)
                    //                    {
                    //                        MessageBox.Show(string.Format("Found {0} records\nFirst Record name is {1}", Result.Entities.Count, Result.Entities.FirstOrDefault().GetAttributeValue<string>("name")));
                    //                    }


                    //                    // Core API using SDK OOTB
                    //                    CreateRequest req = new CreateRequest();
                    //                    Entity accENt = new Entity("account");
                    //                    accENt.Attributes.Add("name", "TESTFOO");
                    //                    req.Target = accENt;
                    //                    CreateResponse res = (CreateResponse)svcClient.OrganizationServiceProxy.Execute(req);
                    //                    //CreateResponse res = (CreateResponse)svcClient.ExecuteCrmOrganizationRequest(req, "MyAccountCreate");
                    //                    MessageBox.Show(res.id.ToString());



                    //                    // Using Xrm.Tooling helpers.
                    //                    Dictionary<string, CrmDataTypeWrapper> newFields = new Dictionary<string, CrmDataTypeWrapper>();
                    //                    // Create a new Record. - Account
                    //                    newFields.Add("name", new CrmDataTypeWrapper("CrudTestAccount", CrmFieldType.String));
                    //                    Guid guAcctId = svcClient.CreateNewRecord("account", newFields);

                    //                    MessageBox.Show(string.Format("New Record Created {0}", guAcctId));
                }
            }
            #endregion
        }
        [STAThread] // Required to support the interactive login experience
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    // Create any entity records that the demonstration code requires
                    SetUpSample(service);
                    #region Demonstrate
                    // Retrieve the system user ID of the user to impersonate.
                    var orgContext = new OrganizationServiceContext(service);
                    _userId = (from user in orgContext.CreateQuery <SystemUser>()
                               where user.FullName == "Kevin Cook"
                               select user.SystemUserId.Value).FirstOrDefault();

                    // To impersonate another user, set the OrganizationServiceProxy.CallerId
                    // property to the ID of the other user.
                    service.CallerId = _userId;

                    // Instantiate an account object.
                    // See 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"
                    };

                    // Create an account record named Fourth Coffee.
                    _accountId = service.Create(account);
                    Console.Write("{0} {1} created, ", account.LogicalName, account.Name);
                    //</snippetImpersonateWithOnBehalfOfPrivilege2>

                    // Retrieve the account containing several of its attributes.
                    // CreatedBy should reference the impersonated SystemUser.
                    // CreatedOnBehalfBy should reference the running SystemUser.
                    ColumnSet cols = new ColumnSet(
                        "name",
                        "createdby",
                        "createdonbehalfby",
                        "address1_postalcode",
                        "lastusedincampaign");

                    Account retrievedAccount =
                        (Account)service.Retrieve(Account.EntityLogicalName,
                                                  _accountId, cols);
                    Console.Write("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.
                    service.Update(retrievedAccount);
                    Console.Write("updated, ");
                    #endregion Demonstrate

                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Microsoft Dataverse";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Esempio n. 15
0
        [STAThread] // Added to support UX
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    #region Sample Code
                    //////////////////////////////////////////////
                    #region Set up
                    SetUpSample(service);
                    #endregion Set up
                    #region Demonstrate

                    // Create the count metric, setting the Metric Type to 'Count' by
                    // setting IsAmount to false.
                    Metric sampleMetric = new Metric()
                    {
                        Name     = "Sample Count Metric",
                        IsAmount = false,
                    };
                    _metricId       = service.Create(sampleMetric);
                    sampleMetric.Id = _metricId;

                    Console.Write("Created phone call metric, ");

                    #region Create RollupFields

                    // Create RollupField which targets completed (received) phone calls.
                    RollupField actual = new RollupField()
                    {
                        SourceEntity           = PhoneCall.EntityLogicalName,
                        GoalAttribute          = "actualinteger",
                        SourceState            = 1,
                        SourceStatus           = 4,
                        EntityForDateAttribute = PhoneCall.EntityLogicalName,
                        DateAttribute          = "actualend",
                        MetricId = sampleMetric.ToEntityReference()
                    };
                    _actualId = service.Create(actual);

                    Console.Write("created actual revenue RollupField, ");

                    // Create RollupField which targets open (in-progress) phone calls.
                    RollupField inprogress = new RollupField()
                    {
                        SourceEntity           = PhoneCall.EntityLogicalName,
                        GoalAttribute          = "inprogressinteger",
                        SourceState            = 0,
                        EntityForDateAttribute = PhoneCall.EntityLogicalName,
                        DateAttribute          = "createdon",
                        MetricId = sampleMetric.ToEntityReference()
                    };
                    _inprogressId = service.Create(inprogress);

                    Console.Write("created in-progress revenue RollupField, ");

                    #endregion

                    #region Create the goal rollup queries

                    // Note: Formatting the FetchXml onto multiple lines in the following
                    // rollup queries causes the length property to be greater than 1,000
                    // chars and will cause an exception.

                    // The following query locates closed incoming phone calls.
                    GoalRollupQuery goalRollupQuery = new GoalRollupQuery()
                    {
                        Name            = "Example Goal Rollup Query - Actual",
                        QueryEntityType = PhoneCall.EntityLogicalName,
                        FetchXml        = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'><entity name='phonecall'><attribute name='subject'/><attribute name='statecode'/><attribute name='prioritycode'/><attribute name='scheduledend'/><attribute name='createdby'/><attribute name='regardingobjectid'/><attribute name='activityid'/><order attribute='subject' descending='false'/><filter type='and'><condition attribute='directioncode' operator='eq' value='0'/><condition attribute='statecode' operator='eq' value='1' /></filter></entity></fetch>"
                    };
                    _rollupQueryIds.Add(service.Create(goalRollupQuery));
                    goalRollupQuery.Id = _rollupQueryIds[0];

                    // The following query locates open incoming phone calls.
                    GoalRollupQuery inProgressGoalRollupQuery = new GoalRollupQuery()
                    {
                        Name            = "Example Goal Rollup Query - InProgress",
                        QueryEntityType = PhoneCall.EntityLogicalName,
                        FetchXml        = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'><entity name='phonecall'><attribute name='subject'/><attribute name='statecode'/><attribute name='prioritycode'/><attribute name='scheduledend'/><attribute name='createdby'/><attribute name='regardingobjectid'/><attribute name='activityid'/><order attribute='subject' descending='false'/><filter type='and'><condition attribute='directioncode' operator='eq' value='0'/><condition attribute='statecode' operator='eq' value='0' /></filter></entity></fetch>"
                    };
                    _rollupQueryIds.Add(service.Create(inProgressGoalRollupQuery));
                    inProgressGoalRollupQuery.Id = _rollupQueryIds[1];

                    Console.Write("created rollup queries for incoming phone calls.\n");
                    Console.WriteLine();

                    #endregion

                    #region Create a goal to track the open incoming phone calls.

                    // Create the goal.
                    Goal goal = new Goal()
                    {
                        Title = "Sample Goal",
                        RollupOnlyFromChildGoals      = false,
                        ConsiderOnlyGoalOwnersRecords = false,
                        TargetInteger = 5,
                        RollupQueryActualIntegerId     = goalRollupQuery.ToEntityReference(),
                        RollUpQueryInprogressIntegerId =
                            inProgressGoalRollupQuery.ToEntityReference(),
                        IsFiscalPeriodGoal = false,
                        MetricId           = sampleMetric.ToEntityReference(),
                        GoalOwnerId        = new EntityReference
                        {
                            Id          = _salesManagerId,
                            LogicalName = SystemUser.EntityLogicalName
                        },
                        OwnerId = new EntityReference
                        {
                            Id          = _salesManagerId,
                            LogicalName = SystemUser.EntityLogicalName
                        },
                        GoalStartDate = DateTime.Today.AddDays(-1),
                        GoalEndDate   = DateTime.Today.AddDays(30)
                    };
                    _goalId = service.Create(goal);
                    goal.Id = _goalId;

                    Console.WriteLine("Created goal");
                    Console.WriteLine("-------------------");
                    Console.WriteLine("Target: {0}", goal.TargetInteger.Value);
                    Console.WriteLine("Goal owner: {0}", goal.GoalOwnerId.Id);
                    Console.WriteLine("Goal Start Date: {0}", goal.GoalStartDate);
                    Console.WriteLine("Goal End Date: {0}", goal.GoalEndDate);
                    Console.WriteLine("<End of Listing>");
                    Console.WriteLine();

                    #endregion

                    #region Calculate rollup and display result

                    // Calculate roll-up of the goal.
                    RecalculateRequest recalculateRequest = new RecalculateRequest()
                    {
                        Target = goal.ToEntityReference()
                    };
                    service.Execute(recalculateRequest);

                    Console.WriteLine("Calculated roll-up of goal.");
                    Console.WriteLine();

                    // Retrieve and report 3 different computed values for the goal
                    // - Percentage
                    // - Actual (Integer)
                    // - In-Progress (Integer)
                    QueryExpression retrieveValues = new QueryExpression()
                    {
                        EntityName = Goal.EntityLogicalName,
                        ColumnSet  = new ColumnSet(
                            "title",
                            "percentage",
                            "actualinteger",
                            "inprogressinteger")
                    };
                    EntityCollection ec = service.RetrieveMultiple(retrieveValues);

                    // Compute and display the results.
                    for (int i = 0; i < ec.Entities.Count; i++)
                    {
                        Goal temp = (Goal)ec.Entities[i];
                        Console.WriteLine("Roll-up details for goal: {0}", temp.Title);
                        Console.WriteLine("---------------");
                        Console.WriteLine("Percentage Achieved: {0}",
                                          temp.Percentage);
                        Console.WriteLine("Actual (Integer): {0}",
                                          temp.ActualInteger.Value);
                        Console.WriteLine("In-Progress (Integer): {0}",
                                          temp.InProgressInteger.Value);
                        Console.WriteLine("<End of Listing>");
                    }

                    Console.WriteLine();

                    #endregion

                    #region Update goal to override the actual rollup value

                    // Override the actual and in-progress values of the goal.
                    // To prevent rollup values to be overwritten during next Recalculate operation,
                    // set: goal.IsOverridden = true;

                    goal.IsOverride        = true;
                    goal.ActualInteger     = 10;
                    goal.InProgressInteger = 5;

                    // Update the goal.
                    UpdateRequest update = new UpdateRequest()
                    {
                        Target = goal
                    };
                    service.Execute(update);

                    Console.WriteLine("Goal actual and in-progress values overridden.");
                    Console.WriteLine();

                    #endregion

                    #region Retrieve result of manual override

                    // Retrieve and report 3 different computed values for the goal
                    // - Percentage
                    // - Actual (Integer)
                    // - In-Progress (Integer)
                    retrieveValues = new QueryExpression()
                    {
                        EntityName = Goal.EntityLogicalName,
                        ColumnSet  = new ColumnSet(
                            "title",
                            "percentage",
                            "actualinteger",
                            "inprogressinteger")
                    };
                    ec = service.RetrieveMultiple(retrieveValues);

                    // Compute and display the results.
                    for (int i = 0; i < ec.Entities.Count; i++)
                    {
                        Goal temp = (Goal)ec.Entities[i];
                        Console.WriteLine("Roll-up details for goal: {0}", temp.Title);
                        Console.WriteLine("---------------");
                        Console.WriteLine("Percentage Achieved: {0}",
                                          temp.Percentage);
                        Console.WriteLine("Actual (Integer): {0}",
                                          temp.ActualInteger.Value);
                        Console.WriteLine("In-Progress (Integer): {0}",
                                          temp.InProgressInteger.Value);
                        Console.WriteLine("<End of Listing>");
                    }

                    Console.WriteLine();

                    #endregion

                    #region Close the goal

                    // Close the goal.
                    SetStateRequest closeGoal = new SetStateRequest()
                    {
                        EntityMoniker = goal.ToEntityReference(),
                        State         = new OptionSetValue(1),
                        Status        = new OptionSetValue(1)
                    };

                    Console.WriteLine("Goal closed.");

                    #endregion
                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                #endregion Demonstrate
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            #endregion Sample Code

            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
        [STAThread] // Added to support UX
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    #region Sample Code
                    /////////////////////////////////////////////
                    #region Set up
                    SetUpSample(service);
                    #endregion Set up
                    #region Demonstrate

                    // Create Field Security Profile.
                    var managersProfile = new FieldSecurityProfile();
                    managersProfile.Name = "Managers";
                    profileId            = service.Create(managersProfile);
                    Console.Write("Created Profile, ");

                    // Add team to profile.
                    var teamToProfile = new AssociateRequest()
                    {
                        Target = new EntityReference(FieldSecurityProfile.EntityLogicalName,
                                                     profileId),
                        RelatedEntities = new EntityReferenceCollection()
                        {
                            new EntityReference(Team.EntityLogicalName, teamId)
                        },
                        Relationship = new Relationship("teamprofiles_association")
                    };
                    service.Execute(teamToProfile);

                    // Add user to the profile.
                    var userToProfile = new AssociateRequest()
                    {
                        Target = new EntityReference(FieldSecurityProfile.EntityLogicalName,
                                                     profileId),
                        RelatedEntities = new EntityReferenceCollection()
                        {
                            new EntityReference(SystemUser.EntityLogicalName, userId)
                        },
                        Relationship = new Relationship("systemuserprofiles_association")
                    };
                    service.Execute(userToProfile);

                    // Create custom activity entity.
                    var req = new CreateEntityRequest()
                    {
                        Entity = new EntityMetadata
                        {
                            LogicalName           = "new_tweet",
                            DisplayName           = new Label("Tweet", 1033),
                            DisplayCollectionName = new Label("Tweet", 1033),
                            OwnershipType         = OwnershipTypes.UserOwned,
                            SchemaName            = "New_Tweet",
                            IsActivity            = true,
                            IsAvailableOffline    = true,
                            IsAuditEnabled        = new BooleanManagedProperty(true),
                            IsMailMergeEnabled    = new BooleanManagedProperty(false),
                        },
                        HasActivities    = false,
                        HasNotes         = true,
                        PrimaryAttribute = new StringAttributeMetadata()
                        {
                            SchemaName    = "Subject",
                            LogicalName   = "subject",
                            RequiredLevel = new AttributeRequiredLevelManagedProperty(
                                AttributeRequiredLevel.None),
                            MaxLength   = 100,
                            DisplayName = new Label("Subject", 1033)
                        }
                    };
                    service.Execute(req);
                    Console.Write("Entity Created, ");

                    // Add privileges for the Tweet entity to the Marketing Role.
                    var privileges = new RolePrivilege[3];

                    // SDK: prvCreateActivity
                    privileges[0]             = new RolePrivilege();
                    privileges[0].PrivilegeId = new Guid("{091DF793-FE5E-44D4-B4CA-7E3F580C4664}");
                    privileges[0].Depth       = PrivilegeDepth.Global;

                    // SDK: prvReadActivity
                    privileges[1]             = new RolePrivilege();
                    privileges[1].PrivilegeId = new Guid("{650C14FE-3521-45FE-A000-84138688E45D}");
                    privileges[1].Depth       = PrivilegeDepth.Global;

                    // SDK: prvWriteActivity
                    privileges[2]             = new RolePrivilege();
                    privileges[2].PrivilegeId = new Guid("{0DC8F72C-57D5-4B4D-8892-FE6AAC0E4B81}");
                    privileges[2].Depth       = PrivilegeDepth.Global;

                    // Create and execute the request.
                    var request = new AddPrivilegesRoleRequest()
                    {
                        RoleId     = roleId,
                        Privileges = privileges
                    };
                    var response =
                        (AddPrivilegesRoleResponse)service.Execute(request);

                    // Create custom identity attribute.
                    var attrReq = new CreateAttributeRequest()
                    {
                        Attribute = new StringAttributeMetadata()
                        {
                            LogicalName   = "new_identity",
                            DisplayName   = new Label("Identity", 1033),
                            SchemaName    = "New_Identity",
                            MaxLength     = 500,
                            RequiredLevel = new AttributeRequiredLevelManagedProperty(
                                AttributeRequiredLevel.Recommended),
                            IsSecured = true
                        },
                        EntityName = "new_tweet"
                    };
                    var identityAttributeResponse =
                        (CreateAttributeResponse)service.Execute(attrReq);
                    identityId = identityAttributeResponse.AttributeId;
                    Console.Write("Identity Created, ");

                    // Create custom message attribute.
                    attrReq = new CreateAttributeRequest()
                    {
                        Attribute = new StringAttributeMetadata()
                        {
                            LogicalName   = "new_message",
                            DisplayName   = new Label("Message", 1033),
                            SchemaName    = "New_Message",
                            MaxLength     = 140,
                            RequiredLevel = new AttributeRequiredLevelManagedProperty(
                                AttributeRequiredLevel.Recommended),
                            IsSecured = true
                        },
                        EntityName = "new_tweet"
                    };
                    var messageAttributeResponse =
                        (CreateAttributeResponse)service.Execute(attrReq);
                    messageId = messageAttributeResponse.AttributeId;
                    Console.Write("Message Created, ");

                    // Create field permission object for Identity.
                    var identityPermission = new FieldPermission();
                    identityPermission.AttributeLogicalName = "new_identity";
                    identityPermission.EntityName           = "new_tweet";
                    identityPermission.CanRead = new OptionSetValue(FieldPermissionType.Allowed);
                    identityPermission.FieldSecurityProfileId = new EntityReference(
                        FieldSecurityProfile.EntityLogicalName, profileId);
                    identityPermissionId = service.Create(identityPermission);
                    Console.Write("Permission Created, ");

                    // Create list for storing retrieved profiles.
                    List <Guid> profileIds = new List <Guid>();

                    // Build query to obtain the field security profiles.
                    var qe = new QueryExpression()
                    {
                        EntityName   = FieldSecurityProfile.EntityLogicalName,
                        ColumnSet    = new ColumnSet("fieldsecurityprofileid"),
                        LinkEntities =
                        {
                            new LinkEntity
                            {
                                LinkFromEntityName = FieldSecurityProfile.EntityLogicalName,
                                LinkToEntityName   = SystemUser.EntityLogicalName,
                                LinkCriteria       =
                                {
                                    Conditions =
                                    {
                                        new ConditionExpression("systemuserid", ConditionOperator.Equal, userId)
                                    }
                                }
                            }
                        }
                    };

                    // Execute the query and obtain the results.
                    var rmRequest = new RetrieveMultipleRequest()
                    {
                        Query = qe
                    };

                    EntityCollection bec = ((RetrieveMultipleResponse)service.Execute(
                                                rmRequest)).EntityCollection;

                    // Extract profiles from query result.
                    foreach (FieldSecurityProfile profileEnt in bec.Entities)
                    {
                        profileIds.Add(profileEnt.FieldSecurityProfileId.Value);
                    }
                    Console.Write("Profiles Retrieved, ");

                    // Retrieve attribute permissions of a FieldSecurityProfile.
                    DataCollection <Entity> dc;

                    // Retrieve the attributes.
                    var qba = new QueryByAttribute(FieldPermission.EntityLogicalName);
                    qba.AddAttributeValue("fieldsecurityprofileid", profileId);
                    qba.ColumnSet = new ColumnSet("attributelogicalname");

                    dc = service.RetrieveMultiple(qba).Entities;
                    Console.Write("Attributes Retrieved. ");

                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                #endregion Demonstrate
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Dynamics CRM";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            #endregion Sample Code
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Esempio n. 17
0
        [STAThread] // Added to support UX
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    #region Sample Code
                    //////////////////////////////////////////////
                    #region Set up
                    SetUpSample(service);
                    #endregion Set up
                    #region Demonstrate

                    // Query using the paging cookie.
                    // Define the paging attributes.
                    // The number of records per page to retrieve.
                    int queryCount = 3;

                    // Initialize the page number.
                    int pageNumber = 1;

                    // Initialize the number of records.
                    int recordCount = 0;

                    // Define the condition expression for retrieving records.

                    var pagecondition = new ConditionExpression();
                    pagecondition.AttributeName = "parentaccountid";
                    pagecondition.Operator      = ConditionOperator.Equal;
                    pagecondition.Values.Add(parentAccountId);

                    // Define the order expression to retrieve the records.
                    var order = new OrderExpression();
                    order.AttributeName = "name";
                    order.OrderType     = OrderType.Ascending;

                    // Create the query expression and add condition.
                    var pagequery = new QueryExpression();
                    pagequery.EntityName = "account";
                    pagequery.Criteria.AddCondition(pagecondition);
                    pagequery.Orders.Add(order);
                    pagequery.ColumnSet.AddColumns("name", "emailaddress1");

                    // Assign the pageinfo properties to the query expression.
                    pagequery.PageInfo            = new PagingInfo();
                    pagequery.PageInfo.Count      = queryCount;
                    pagequery.PageInfo.PageNumber = pageNumber;

                    // The current paging cookie. When retrieving the first page,
                    // pagingCookie should be null.
                    pagequery.PageInfo.PagingCookie = null;
                    Console.WriteLine("Retrieving sample account records in pages...\n");
                    Console.WriteLine("#\tAccount Name\t\tEmail Address");

                    while (true)
                    {
                        // Retrieve the page.
                        EntityCollection results = service.RetrieveMultiple(pagequery);
                        if (results.Entities != null)
                        {
                            // Retrieve all records from the result set.
                            foreach (Account acct in results.Entities)
                            {
                                Console.WriteLine("{0}.\t{1}\t{2}", ++recordCount, acct.Name,
                                                  acct.EMailAddress1);
                            }
                        }

                        // Check for more records, if it returns true.
                        if (results.MoreRecords)
                        {
                            Console.WriteLine("\n****************\nPage number {0}\n****************", pagequery.PageInfo.PageNumber);
                            Console.WriteLine("#\tAccount Name\t\tEmail Address");

                            // 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;
                        }
                    }


                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                #endregion Demonstrate
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            #endregion Sample Code
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
        [STAThread] // Required to support the interactive login experience
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    // Create any entity records that the demonstration code requires
                    SetUpSample(service);

                    #region Demonstrate
                    // Create the target for the request.
                    var target = new EntityReference();

                    // Id is the GUID of the account that is being merged into.
                    // LogicalName is the type of the entity being merged to, as a string
                    target.Id          = _account1Id;
                    target.LogicalName = Account.EntityLogicalName;

                    // Create the request.
                    var merge = new MergeRequest();
                    // SubordinateId is the GUID of the account merging.
                    merge.SubordinateId          = _account2Id;
                    merge.Target                 = target;
                    merge.PerformParentingChecks = false;

                    Console.WriteLine("\nMerging account2 into account1 and adding " +
                                      "\"test\" as Address 1 Line 1");

                    // Create another account to hold new data to merge into the entity.
                    // If you use the subordinate account object, its data will be merged.
                    var updateContent = new Account();
                    updateContent.Address1_Line1 = "test";

                    // Set the content you want updated on the merged account
                    merge.UpdateContent = updateContent;

                    // Execute the request.
                    var merged = (MergeResponse)service.Execute(merge);

                    var mergeeAccount =
                        (Account)service.Retrieve(Account.EntityLogicalName,
                                                  _account2Id, new ColumnSet(allColumns: true));

                    if (mergeeAccount.Merged == true)
                    {
                        var mergedAccount =
                            (Account)service.Retrieve(Account.EntityLogicalName,
                                                      _account1Id, new ColumnSet(allColumns: true));

                        Console.WriteLine("\nAccounts merged successfully into account1");
                        Console.WriteLine("  Name: {0}", mergedAccount.Name);
                        Console.WriteLine("  Description: {0}", mergedAccount.Description);
                        Console.WriteLine("  Number of Employees: {0}",
                                          mergedAccount.NumberOfEmployees);
                        Console.WriteLine("  Address 1 Line 1: {0}",
                                          mergedAccount.Address1_Line1);
                    }
                    #endregion Demonstrate

                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Microsoft Dataverse";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
        private void Connect()
        {
            visitedPath.Add(pnlWaiting.Name);

            var bw = new BackgroundWorker();
            bw.DoWork += (bwSender, evt) =>
            {
                var detail = (ConnectionDetail)evt.Argument;
                evt.Result = detail.GetCrmServiceClient(true);
            };
            bw.RunWorkerCompleted += (bwSender, evt) =>
            {
                if (evt.Error != null)
                {
                    lblDescription.Text = Resources.ConnectionWizard_ErrorHeaderDescription;

                    lblError.Text = evt.Error.Message;

                    if (updatedDetail.UseOsdp)
                    {
                        lblError.Text += "\r\nIf the unique name for your organization is different from the name used in the url you provided, please replace the organization name in the url with the organization unique name";
                    }

                    DisplayPanel(pnlError, null);

                    return;
                }

                CrmServiceClient crmSvc = (CrmServiceClient)evt.Result;

                if (!crmSvc.IsReady)
                {
                    lblDescription.Text = Resources.ConnectionWizard_ErrorHeaderDescription;

                    lblError.Text = crmSvc.LastCrmError;

                    DisplayPanel(pnlError, null);

                    return;
                }

                lblDescription.Text = Resources.ConnectionWizard_SuccessHeaderDescription;

                DisplayPanel(pnlConnected, btnFinish);
                txtConnectionName.Focus();

                serviceClient = crmSvc;
            };
            bw.RunWorkerAsync(updatedDetail);
        }
Esempio n. 20
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Creates the email activity.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            // Create a Lead record on which we will execute the Workflow.
            Lead lead = new Lead()
            {
                FirstName = "Diogo",
                LastName  = "Andrade"
            };

            _leadId = service.Create(lead);
            Console.WriteLine("Created a lead named '{0} {1}' for the workflow request.", lead.FirstName,
                              lead.LastName);

            // Define an anonymous type to define the possible values for
            // process type
            var ProcessType = new
            {
                Definition = 1,
                Activation = 2,
                Template   = 3
            };

            // Define an anonymous type to define the possible values for
            // process category
            var ProcessCategory = new
            {
                Workflow = 0,
                Dialog   = 1,
            };

            // Define an anonymous type to define the possible values for
            // process scope
            var ProcessScope = new
            {
                User         = 1,
                BusinessUnit = 2,
                Deep         = 3,
                Global       = 4
            };

            // Create the Workflow that we will execute.
            Workflow workflow = new Workflow()
            {
                Name          = "Sample Workflow", // friendly name of the record
                Type          = new OptionSetValue(ProcessType.Definition),
                Category      = new OptionSetValue(ProcessCategory.Workflow),
                Scope         = new OptionSetValue(ProcessScope.User),
                OnDemand      = true,
                PrimaryEntity = Lead.EntityLogicalName,
                Xaml          =
                    @"<?xml version=""1.0"" encoding=""utf-16""?>
<Activity x:Class=""ExecuteWorkflowSample"" xmlns=""http://schemas.microsoft.com/netfx/2009/xaml/activities"" xmlns:mva=""clr-namespace:Microsoft.VisualBasic.Activities;assembly=System.Activities, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" xmlns:mxs=""clr-namespace:Microsoft.Xrm.Sdk;assembly=Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" xmlns:mxswa=""clr-namespace:Microsoft.Xrm.Sdk.Workflow.Activities;assembly=Microsoft.Xrm.Sdk.Workflow, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" xmlns:s=""clr-namespace:System;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" xmlns:scg=""clr-namespace:System.Collections.Generic;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" xmlns:srs=""clr-namespace:System.Runtime.Serialization;assembly=System.Runtime.Serialization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" xmlns:this=""clr-namespace:"" xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
  <x:Members>
    <x:Property Name=""InputEntities"" Type=""InArgument(scg:IDictionary(x:String, mxs:Entity))"" />
    <x:Property Name=""CreatedEntities"" Type=""InArgument(scg:IDictionary(x:String, mxs:Entity))"" />
  </x:Members>
  <this:ExecuteWorkflowSample.InputEntities>
    <InArgument x:TypeArguments=""scg:IDictionary(x:String, mxs:Entity)"" />
  </this:ExecuteWorkflowSample.InputEntities>
  <this:ExecuteWorkflowSample.CreatedEntities>
    <InArgument x:TypeArguments=""scg:IDictionary(x:String, mxs:Entity)"" />
  </this:ExecuteWorkflowSample.CreatedEntities>
  <mva:VisualBasic.Settings>Assembly references and imported namespaces for internal implementation</mva:VisualBasic.Settings>
  <mxswa:Workflow>
    <Assign x:TypeArguments=""mxs:Entity"" To=""[CreatedEntities(&quot;CreateStep1_localParameter#Temp&quot;)]"" Value=""[New Entity(&quot;phonecall&quot;)]"" />
    <Sequence DisplayName=""CreateStep1: Set first activity for lead."">
      <Sequence.Variables>
        <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_1"" />
        <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_2"" />
        <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_3"" />
        <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_4"" />
        <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_5"" />
        <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_6"" />
        <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_7"" />
        <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_8"" />
      </Sequence.Variables>
      <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression"">
        <mxswa:ActivityReference.Arguments>
          <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">CreateCrmType</InArgument>
          <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { Microsoft.Xrm.Sdk.Workflow.WorkflowPropertyType.Boolean, ""True"" }]</InArgument>
          <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType"">
            <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:Boolean"" />
          </InArgument>
          <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_1]</OutArgument>
        </mxswa:ActivityReference.Arguments>
      </mxswa:ActivityReference>
      <mxswa:SetEntityProperty Attribute=""directioncode"" Entity=""[CreatedEntities(&quot;CreateStep1_localParameter#Temp&quot;)]"" EntityName=""phonecall"" Value=""[CreateStep1_1]"">
        <mxswa:SetEntityProperty.TargetType>
          <InArgument x:TypeArguments=""s:Type"">
            <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:Boolean"" />
          </InArgument>
        </mxswa:SetEntityProperty.TargetType>
      </mxswa:SetEntityProperty>
      <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression"">
        <mxswa:ActivityReference.Arguments>
          <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">CreateCrmType</InArgument>
          <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { Microsoft.Xrm.Sdk.Workflow.WorkflowPropertyType.String, ""First call to "", ""String"" }]</InArgument>
          <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType"">
            <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" />
          </InArgument>
          <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_3]</OutArgument>
        </mxswa:ActivityReference.Arguments>
      </mxswa:ActivityReference>
      <mxswa:GetEntityProperty Attribute=""fullname"" Entity=""[InputEntities(&quot;primaryEntity&quot;)]"" EntityName=""lead"" Value=""[CreateStep1_5]"">
        <mxswa:GetEntityProperty.TargetType>
          <InArgument x:TypeArguments=""s:Type"">
            <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" />
          </InArgument>
        </mxswa:GetEntityProperty.TargetType>
      </mxswa:GetEntityProperty>
      <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression"">
        <mxswa:ActivityReference.Arguments>
          <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">SelectFirstNonNull</InArgument>
          <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { CreateStep1_5 }]</InArgument>
          <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType"">
            <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" />
          </InArgument>
          <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_4]</OutArgument>
        </mxswa:ActivityReference.Arguments>
      </mxswa:ActivityReference>
      <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression"">
        <mxswa:ActivityReference.Arguments>
          <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">Add</InArgument>
          <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { CreateStep1_3, CreateStep1_4 }]</InArgument>
          <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType"">
            <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" />
          </InArgument>
          <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_2]</OutArgument>
        </mxswa:ActivityReference.Arguments>
      </mxswa:ActivityReference>
      <mxswa:SetEntityProperty Attribute=""subject"" Entity=""[CreatedEntities(&quot;CreateStep1_localParameter#Temp&quot;)]"" EntityName=""phonecall"" Value=""[CreateStep1_2]"">
        <mxswa:SetEntityProperty.TargetType>
          <InArgument x:TypeArguments=""s:Type"">
            <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" />
          </InArgument>
        </mxswa:SetEntityProperty.TargetType>
      </mxswa:SetEntityProperty>
      <mxswa:GetEntityProperty Attribute=""leadid"" Entity=""[InputEntities(&quot;primaryEntity&quot;)]"" EntityName=""lead"" Value=""[CreateStep1_7]"">
        <mxswa:GetEntityProperty.TargetType>
          <InArgument x:TypeArguments=""s:Type"">
            <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""mxs:EntityReference"" />
          </InArgument>
        </mxswa:GetEntityProperty.TargetType>
      </mxswa:GetEntityProperty>
      <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression"">
        <mxswa:ActivityReference.Arguments>
          <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">SelectFirstNonNull</InArgument>
          <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { CreateStep1_7 }]</InArgument>
          <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType"">
            <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""mxs:EntityReference"" />
          </InArgument>
          <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_6]</OutArgument>
        </mxswa:ActivityReference.Arguments>
      </mxswa:ActivityReference>
      <mxswa:SetEntityProperty Attribute=""regardingobjectid"" Entity=""[CreatedEntities(&quot;CreateStep1_localParameter#Temp&quot;)]"" EntityName=""phonecall"" Value=""[CreateStep1_6]"">
        <mxswa:SetEntityProperty.TargetType>
          <InArgument x:TypeArguments=""s:Type"">
            <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""mxs:EntityReference"" />
          </InArgument>
        </mxswa:SetEntityProperty.TargetType>
      </mxswa:SetEntityProperty>
      <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression"">
        <mxswa:ActivityReference.Arguments>
          <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">CreateCrmType</InArgument>
          <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { Microsoft.Xrm.Sdk.Workflow.WorkflowPropertyType.OptionSetValue, ""1"", ""Picklist"" }]</InArgument>
          <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType"">
            <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""mxs:OptionSetValue"" />
          </InArgument>
          <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_8]</OutArgument>
        </mxswa:ActivityReference.Arguments>
      </mxswa:ActivityReference>
      <mxswa:SetEntityProperty Attribute=""prioritycode"" Entity=""[CreatedEntities(&quot;CreateStep1_localParameter#Temp&quot;)]"" EntityName=""phonecall"" Value=""[CreateStep1_8]"">
        <mxswa:SetEntityProperty.TargetType>
          <InArgument x:TypeArguments=""s:Type"">
            <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""mxs:OptionSetValue"" />
          </InArgument>
        </mxswa:SetEntityProperty.TargetType>
      </mxswa:SetEntityProperty>
      <mxswa:CreateEntity EntityId=""{x:Null}"" DisplayName=""CreateStep1: Set first activity for lead."" Entity=""[CreatedEntities(&quot;CreateStep1_localParameter#Temp&quot;)]"" EntityName=""phonecall"" />
      <Assign x:TypeArguments=""mxs:Entity"" To=""[CreatedEntities(&quot;CreateStep1_localParameter&quot;)]"" Value=""[CreatedEntities(&quot;CreateStep1_localParameter#Temp&quot;)]"" />
      <Persist />
    </Sequence>
  </mxswa:Workflow>
</Activity>"
            };

            _workflowId = service.Create(workflow);
            Console.Write("Created '{0}' to call in the ExecuteWorkflow request, ", workflow.Name);

            SetStateRequest setStateRequest = new SetStateRequest()
            {
                EntityMoniker =
                    new EntityReference(Workflow.EntityLogicalName, _workflowId),
                State  = new OptionSetValue((int)WorkflowState.Activated),
                Status = new OptionSetValue(2)
            };

            service.Execute(setStateRequest);
            Console.WriteLine("and then activated it.");
        }
Esempio n. 21
0
        public Dynamics365DataAccessLayer_Reused()
        {
            var connectionString = "AuthType=Office365;[email protected];Password=;Url=https://.crm6.dynamics.com";

            _crmSvc = new CrmServiceClient(connectionString);
        }
Esempio n. 22
0
        [STAThread] // Added to support UX
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    #region Sample Code
                    //////////////////////////////////////////////
                    #region Set up
                    SetUpSample(service);
                    #endregion Set up
                    #region Demonstrate

                    // Instaniate an account object.
                    var account = new Entity("account");

                    // Set the required attributes. For account, only the name is required.
                    // See the Entity Metadata topic in the SDK documentatio to determine
                    // which attributes must be set for each entity.
                    account["name"] = "Fourth Coffee";

                    // Create an account record named Fourth Coffee.
                    accountId = service.Create(account);

                    Console.Write("{0} {1} created, ", account.LogicalName, account.Attributes["name"]);

                    // Create a column set to define which attributes should be retrieved.
                    var attributes = new ColumnSet(new string[] { "name", "ownerid" });

                    // Retrieve the account and its name and ownerid attributes.
                    account = service.Retrieve(account.LogicalName, accountId, attributes);
                    Console.Write("retrieved, ");

                    // Update the postal code attribute.
                    account["address1_postalcode"] = "98052";

                    // The address 2 postal code was set accidentally, so set it to null.
                    account["address2_postalcode"] = null;

                    // Shows use of Money.
                    account["revenue"] = new Money(5000000);

                    // Shows use of boolean.
                    account["creditonhold"] = false;

                    // Update the account.
                    service.Update(account);
                    Console.WriteLine("and updated.");

                    // Delete the account.
                    bool deleteRecords = true;

                    if (prompt)
                    {
                        Console.WriteLine("\nDo you want these entity records deleted? (y/n) [y]: ");
                        String answer = Console.ReadLine();

                        deleteRecords = (answer.StartsWith("y") || answer.StartsWith("Y") || answer == String.Empty);
                    }

                    if (deleteRecords)
                    {
                        service.Delete("account", accountId);

                        Console.WriteLine("Entity record(s) have been deleted.");
                    }

                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                #endregion Demonstrate
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Dynamics CRM";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            #endregion Sample Code
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Esempio n. 23
0
        /// <summary>
        /// Creates any entity records that this sample requires.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            #region Create or Retrieve the necessary system users

            // Retrieve the ldapPath
            String ldapPath = String.Empty;
            // Retrieve the sales team - 1 sales manager and 2 sales representatives.
            _salesManagerId =
                SystemUserProvider.RetrieveSalesManager(service, ref ldapPath);
            _salesRepresentativeIds =
                SystemUserProvider.RetrieveSalespersons(service, ref ldapPath);

            #endregion

            #region Create PhoneCall record and supporting account

            Account account = new Account
            {
                Name = "Margie's Travel",
                Address1_PostalCode = "99999"
            };
            _accountId = (service.Create(account));
            account.Id = _accountId;

            // Create Guids for PhoneCalls
            _phoneCallId  = Guid.NewGuid();
            _phoneCall2Id = Guid.NewGuid();

            // Create ActivityPartys for the phone calls' "From" field.
            ActivityParty activityParty = new ActivityParty()
            {
                PartyId    = account.ToEntityReference(),
                ActivityId = new EntityReference
                {
                    Id          = _phoneCallId,
                    LogicalName = PhoneCall.EntityLogicalName,
                },
                ParticipationTypeMask = new OptionSetValue(9),
            };

            ActivityParty activityPartyClosed = new ActivityParty()
            {
                PartyId    = account.ToEntityReference(),
                ActivityId = new EntityReference
                {
                    Id          = _phoneCall2Id,
                    LogicalName = PhoneCall.EntityLogicalName,
                },
                ParticipationTypeMask = new OptionSetValue(9)
            };

            // Create an open phone call.
            PhoneCall phoneCall = new PhoneCall()
            {
                Id            = _phoneCallId,
                Subject       = "Sample Phone Call",
                DirectionCode = false,
                To            = new ActivityParty[] { activityParty },
                OwnerId       = new EntityReference("systemuser", _salesRepresentativeIds[0]),
                ActualEnd     = DateTime.Now
            };
            service.Create(phoneCall);

            // Close the first phone call.
            SetStateRequest closePhoneCall = new SetStateRequest()
            {
                EntityMoniker = phoneCall.ToEntityReference(),
                State         = new OptionSetValue(1),
                Status        = new OptionSetValue(4)
            };
            service.Execute(closePhoneCall);

            // Create a second phone call.
            phoneCall = new PhoneCall()
            {
                Id            = _phoneCall2Id,
                Subject       = "Sample Phone Call 2",
                DirectionCode = true,
                To            = new ActivityParty[] { activityParty },
                OwnerId       = new EntityReference("systemuser", _salesRepresentativeIds[1]),
                ActualEnd     = DateTime.Now
            };
            service.Create(phoneCall);

            // Close the second phone call.
            closePhoneCall = new SetStateRequest()
            {
                EntityMoniker = phoneCall.ToEntityReference(),
                State         = new OptionSetValue(1),
                Status        = new OptionSetValue(4)
            };
            service.Execute(closePhoneCall);

            #endregion
        }
Esempio n. 24
0
        [STAThread] // Required to support the interactive login experience
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    // Create any entity records that the demonstration code requires
                    SetUpSample(service);
                    #region Demonstrate
                    // Define some anonymous types to define the range
                    // of possible connection property values.
                    var Categories = new
                    {
                        Business = 1,
                        Family   = 2,
                        Social   = 3,
                        Sales    = 4,
                        Other    = 5
                    };

                    // Update the connectionrole instance.
                    ConnectionRole connectionRole = new ConnectionRole
                    {
                        ConnectionRoleId = _connectionRoleId,
                        Name             = "Updated Connection Role",
                        Description      = "This is an updated connection role.",
                        Category         = new OptionSetValue(Categories.Other)
                    };

                    service.Update(connectionRole);


                    Console.WriteLine("Updated the connectionrole instance.");
                    #endregion Demonstrate

                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Esempio n. 25
0
        [STAThread] // Required to support the interactive login experience
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    #region Demonstrate
                    // Create any entity records that the demonstration code requires
                    SetUpSample(service);
                    var request = new RetrieveAllEntitiesRequest()
                    {
                        EntityFilters         = EntityFilters.Relationships,
                        RetrieveAsIfPublished = true
                    };

                    // Retrieve the MetaData.
                    var response = (RetrieveAllEntitiesResponse)service.Execute(request);


                    // Create an instance of StreamWriter to write text to a file.
                    // The using statement also closes the StreamWriter.
                    // To view this file, right click the file and choose open with Excel.
                    // Excel will figure out the schema and display the information in columns.

                    String filename = String.Concat("RelationshipInfo.xml");
                    using (var sw = new StreamWriter(filename))
                    {
                        // Create Xml Writer.
                        var metadataWriter = new XmlTextWriter(sw);

                        // Start Xml File.
                        metadataWriter.WriteStartDocument();

                        // Metadata Xml Node.
                        metadataWriter.WriteStartElement("Metadata");

                        foreach (EntityMetadata currentEntity in response.EntityMetadata)
                        {
                            //if (currentEntity.IsIntersect.Value == false)
                            if (true)
                            {
                                // Start Entity Node
                                metadataWriter.WriteStartElement("Entity");

                                // Write the Entity's Information.
                                metadataWriter.WriteElementString("EntitySchemaName", currentEntity.SchemaName);

                                // Start OneToManyRelationships Node
                                metadataWriter.WriteStartElement("OneToManyRelationships");

                                foreach (OneToManyRelationshipMetadata currentRelationship in currentEntity.OneToManyRelationships)
                                {
                                    // Start  Node
                                    metadataWriter.WriteStartElement("Relationship");

                                    metadataWriter.WriteElementString("OtoM_SchemaName", currentRelationship.SchemaName);
                                    metadataWriter.WriteElementString("OtoM_ReferencingEntity", currentRelationship.ReferencingEntity);
                                    metadataWriter.WriteElementString("OtoM_ReferencedEntity", currentRelationship.ReferencedEntity);
                                    // End  Node
                                    metadataWriter.WriteEndElement();
                                }

                                // End OneToManyRelationships Node
                                metadataWriter.WriteEndElement();

                                // Start ManyToManyRelationships Node
                                metadataWriter.WriteStartElement("ManyToManyRelationships");


                                foreach (ManyToManyRelationshipMetadata currentRelationship in currentEntity.ManyToManyRelationships)
                                {
                                    // Start  Node
                                    metadataWriter.WriteStartElement("Relationship");

                                    metadataWriter.WriteElementString("MtoM_SchemaName", currentRelationship.SchemaName);
                                    metadataWriter.WriteElementString("MtoM_Entity1", currentRelationship.Entity1LogicalName);
                                    metadataWriter.WriteElementString("MtoM_Entity2", currentRelationship.Entity2LogicalName);
                                    metadataWriter.WriteElementString("IntersectEntity", currentRelationship.IntersectEntityName);
                                    // End  Node
                                    metadataWriter.WriteEndElement();
                                }

                                // End ManyToManyRelationships Node
                                metadataWriter.WriteEndElement();

                                // Start ManyToOneRelationships Node
                                metadataWriter.WriteStartElement("ManyToOneRelationships");


                                foreach (OneToManyRelationshipMetadata currentRelationship in currentEntity.ManyToOneRelationships)
                                {
                                    // Start  Node
                                    metadataWriter.WriteStartElement("Relationship");

                                    metadataWriter.WriteElementString("MtoO_SchemaName", currentRelationship.SchemaName);
                                    metadataWriter.WriteElementString("MtoO_ReferencingEntity", currentRelationship.ReferencingEntity);
                                    metadataWriter.WriteElementString("MtoO_ReferencedEntity", currentRelationship.ReferencedEntity);
                                    // End  Node
                                    metadataWriter.WriteEndElement();
                                }

                                // End ManyToOneRelationships Node
                                metadataWriter.WriteEndElement();

                                // End Relationships Node
                                // metadataWriter.WriteEndElement();



                                // End Entity Node
                                metadataWriter.WriteEndElement();
                            }
                        }

                        // End Metadata Xml Node
                        metadataWriter.WriteEndElement();
                        metadataWriter.WriteEndDocument();

                        // Close xml writer.
                        metadataWriter.Close();
                    }



                    Console.WriteLine("Done.");

                    #endregion Demonstrate
                }
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Microsoft Dataverse";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
 public WorkflowRunnerController(CrmServiceClient crmClient, OrganizationServiceContext context, IOrganizationService orgSevice)
 {
     CrmServiceClient = crmClient;
     ServiceContext   = context;
     OrgService       = orgSevice;
 }
Esempio n. 27
0
 private static void CleanUpSample(CrmServiceClient service)
 {
     DeleteRequiredRecords(service, prompt);
 }
Esempio n. 28
0
        private static void CreateMarketingList(CrmServiceClient service)
        {
            Console.WriteLine("=== Creating the Marketing List ===");
            // Create the marketing list.  Make it static because members are going to be
            // added to the list.
            var list = new List
            {
                CreatedFromCode = new OptionSetValue((int)ListCreatedFromCode.Contact),
                ListName        = "Sample Contact Marketing List",
                Type            = MarketingListType.Static
            };

            _marketingListId = service.Create(list);

            NotifyEntityCreated(List.EntityLogicalName, _marketingListId);

            // Add a list of contacts to the marketing list.
            var addMemberListReq = new AddListMembersListRequest
            {
                MemberIds = new[] { _contactIdList[0], _contactIdList[2] },
                ListId    = _marketingListId
            };

            service.Execute(addMemberListReq);

            Console.WriteLine("  Contacts with GUIDs \r\n\t{{{0}}}\r\n\tand {{{1}}}\r\n  were added to the list.",
                              _contactIdList[0], _contactIdList[1]);

            // Copy the marketing list.  First create a new one, and then copy over the
            // members.
            list.ListName          = list.ListName + " Copy";
            _copiedMarketingListId = service.Create(list);
            var copyRequest = new CopyMembersListRequest
            {
                SourceListId = _marketingListId,
                TargetListId = _copiedMarketingListId
            };

            service.Execute(copyRequest);

            // Add a single contact to the copied marketing list.
            var addMemberReq = new AddMemberListRequest
            {
                EntityId = _contactIdList[1],
                ListId   = _copiedMarketingListId
            };

            service.Execute(addMemberReq);

            Console.WriteLine("  Contact with GUID\r\n\t{{{0}}}\r\n  was added to the list.",
                              _contactIdList[1]);

            // Qualify the marketing list.
            var qualifyRequest = new QualifyMemberListRequest
            {
                OverrideorRemove = OverrideOrRemove.Override,
                MembersId        = new[] { _contactIdList[0], _contactIdList[1] },
                ListId           = _copiedMarketingListId
            };

            service.Execute(qualifyRequest);

            Console.WriteLine("  Qualified the copied marketing list so that it only\r\n    includes the first two members.");
        }
        public static void SetCurrentConnection(CrmServiceClient client, string type, DTE dte)
        {
            Globals globals = dte.Globals;

            globals["CurrentConnection" + type] = client;
        }
Esempio n. 30
0
        private static void CreateRequiredRecords(CrmServiceClient service)
        {
            // Create an account.
            var account = new Account
            {
                Name = "Litware, Inc.",
                Address1_StateOrProvince = "Colorado"
            };

            _accountId = service.Create(account);

            // Create the contacts.
            var contact = new Contact
            {
                FirstName                = "Ben",
                LastName                 = "Andrews",
                EMailAddress1            = "*****@*****.**",
                Address1_City            = "Redmond",
                Address1_StateOrProvince = "WA",
                Address1_Telephone1      = "(206)555-5555",
                ParentCustomerId         = new EntityReference
                {
                    Id          = _accountId,
                    LogicalName = account.LogicalName
                }
            };

            _contactIdList.Add(service.Create(contact));

            contact = new Contact
            {
                FirstName                = "Colin",
                LastName                 = "Wilcox",
                EMailAddress1            = "*****@*****.**",
                Address1_City            = "Bellevue",
                Address1_StateOrProvince = "WA",
                Address1_Telephone1      = "(425)555-5555",
                ParentCustomerId         = new EntityReference
                {
                    Id          = _accountId,
                    LogicalName = account.LogicalName
                }
            };
            _contactIdList.Add(service.Create(contact));

            contact = new Contact
            {
                FirstName                = "Lisa",
                LastName                 = "Andrews",
                EMailAddress1            = "*****@*****.**",
                Address1_City            = "Redmond",
                Address1_StateOrProvince = "WA",
                Address1_Telephone1      = "(206)555-5556",
                ParentCustomerId         = new EntityReference
                {
                    Id          = _accountId,
                    LogicalName = account.LogicalName
                }
            };
            _contactIdList.Add(service.Create(contact));
        }
Esempio n. 31
0
 public CrmService(string connectionString)
 {
     WebRequest.DefaultWebProxy = WebRequest.GetSystemWebProxy();
     WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials;
     _connectionString = connectionString;
     _connection = new CrmServiceClient(_connectionString);
 }
Esempio n. 32
0
        private static void DistributeCampaign(CrmServiceClient service)
        {
            Console.WriteLine("=== Creating and Distributing the Campaign ===");
            // Create the campaign.
            var campaign = new Campaign
            {
                Name = "Sample Campaign"
            };

            _originalCampaignId = service.Create(campaign);

            NotifyEntityCreated(Campaign.EntityLogicalName, _originalCampaignId);

            // Copy the campaign.
            var campaignCopyRequest = new CopyCampaignRequest
            {
                BaseCampaign = _originalCampaignId
            };

            var copyCampaignResponse =
                (CopyCampaignResponse)service.Execute(campaignCopyRequest);

            _campaignId = copyCampaignResponse.CampaignCopyId;

            Console.WriteLine("  Copied the campaign to new campaign with GUID \r\n\t{{{0}}}",
                              _campaignId);

            var activity = new CampaignActivity
            {
                Subject           = "Sample phone call",
                ChannelTypeCode   = new OptionSetValue((int)CampaignActivityChannelTypeCode.Phone),
                RegardingObjectId = new EntityReference(
                    Campaign.EntityLogicalName, _campaignId)
            };

            _campaignActivityId = service.Create(activity);

            NotifyEntityCreated(CampaignActivity.EntityLogicalName, _campaignActivityId);

            // Find the current user to determine who the owner of the activity should be.
            var whoAmI      = new WhoAmIRequest();
            var currentUser = (WhoAmIResponse)service.Execute(whoAmI);

            // Add the marketing list created earlier to the campaign.
            var addListToCampaignRequest = new AddItemCampaignRequest
            {
                CampaignId = _campaignId,
                EntityId   = _copiedMarketingListId,
                EntityName = List.EntityLogicalName,
            };

            service.Execute(addListToCampaignRequest);

            Console.WriteLine("  Added the marketing list to the campaign.");

            // Add the marketing list created earlier to the campaign activity.
            var addListToActivityRequest = new AddItemCampaignActivityRequest
            {
                CampaignActivityId = _campaignActivityId,
                ItemId             = _copiedMarketingListId,
                EntityName         = List.EntityLogicalName
            };

            service.Execute(addListToActivityRequest);

            Console.WriteLine("  Added the marketing list to the campaign activity.");

            // Create the phone call to use for distribution.
            var phonecall = new PhoneCall
            {
                Subject = "Sample Phone Call"
            };

            // Distribute and execute the campaign activity.
            // PostWorkflowEvent signals Microsoft Dynamics CRM to actually create the phone call activities.
            // Propagate also signals to Microsoft Dynamics CRM to create the phone call activities.
            // OwnershipOptions indicates whom the created activities should be assigned
            // to.
            var distributeRequest = new DistributeCampaignActivityRequest
            {
                Activity           = phonecall,
                CampaignActivityId = _campaignActivityId,
                Owner = new EntityReference(
                    SystemUser.EntityLogicalName, currentUser.UserId),
                OwnershipOptions  = PropagationOwnershipOptions.Caller,
                PostWorkflowEvent = true,
                Propagate         = true,
                SendEmail         = false,
            };

            var distributeResponse =
                (DistributeCampaignActivityResponse)service.Execute(distributeRequest);

            Console.WriteLine("  Distributed and executed the campaign activity to the marketing list.");

            // Retrieve the members that were distributed to.
            var retrieveMembersRequest = new RetrieveMembersBulkOperationRequest
            {
                BulkOperationId     = distributeResponse.BulkOperationId,
                BulkOperationSource = (int)BulkOperationSource.CampaignActivity,
                EntitySource        = (int)EntitySource.Contact,
                Query = new QueryExpression(Contact.EntityLogicalName)
            };

            var retrieveMembersResponse = (RetrieveMembersBulkOperationResponse)
                                          service.Execute(retrieveMembersRequest);

            Console.WriteLine("  Contacts with the following GUIDs were distributed to:");
            foreach (var member in retrieveMembersResponse.EntityCollection.Entities)
            {
                Console.WriteLine("\t{{{0}}}", member.Id);
            }
        }
Esempio n. 33
0
        /// <summary>
        /// This raises and processes Success
        /// </summary>
        private void ProcessSuccess()
        {
            resetUiFlag = true;
            bIsConnectedComplete = true;
            CrmSvc = mgr.CrmSvc;

            View.CrmLoginCtrl.GoBackToLogin();
            Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal,
                new System.Action(() =>
                {
                    View.Title = "Notification from Parent";
                    View.CrmLoginCtrl.IsEnabled = true;
                }
            ));

            View.DialogResult = true;
            View.Close();

            resetUiFlag = false;
        }
Esempio n. 34
0
        [STAThread] // Required to support the interactive login experience
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    // Create any entity records that the demonstration code requires
                    SetUpSample(service);
                    #region Demonstrate
                    // Define the request object and pass to the service.
                    var createOptionSetRequest = new CreateOptionSetRequest
                    {
                        // Create a global option set (OptionSetMetadata).
                        OptionSet = new OptionSetMetadata
                        {
                            Name          = _globalOptionSetName,
                            DisplayName   = new Label("Example Option Set", _languageCode),
                            IsGlobal      = true,
                            OptionSetType = OptionSetType.Picklist,
                            Options       =
                            {
                                new OptionMetadata(new Label("Open",      _languageCode), null),
                                new OptionMetadata(new Label("Suspended", _languageCode), null),
                                new OptionMetadata(new Label("Cancelled", _languageCode), null),
                                new OptionMetadata(new Label("Closed",    _languageCode), null)
                            }
                        }
                    };

                    // Execute the request.
                    CreateOptionSetResponse optionsResp =
                        (CreateOptionSetResponse)service.Execute(createOptionSetRequest);

                    //</snippetWorkwithGlobalOptionSets2>
                    #endregion How to create global option set

                    // Store the option set's id as it will be needed to find all the
                    // dependent components.
                    _optionSetId = optionsResp.OptionSetId;
                    Console.WriteLine("The global option set has been created.");

                    #region How to create a picklist linked to the global option set
                    //<snippetWorkwithGlobalOptionSets3>
                    // Create a Picklist linked to the option set.
                    // Specify which entity will own the picklist, and create it.
                    var createRequest = new CreateAttributeRequest
                    {
                        EntityName = Contact.EntityLogicalName,
                        Attribute  = new PicklistAttributeMetadata
                        {
                            SchemaName    = "sample_examplepicklist",
                            LogicalName   = "sample_examplepicklist",
                            DisplayName   = new Label("Example Picklist", _languageCode),
                            RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),

                            // In order to relate the picklist to the global option set, be sure
                            // to specify the two attributes below appropriately.
                            // Failing to do so will lead to errors.
                            OptionSet = new OptionSetMetadata
                            {
                                IsGlobal = true,
                                Name     = _globalOptionSetName
                            }
                        }
                    };

                    service.Execute(createRequest);
                    //</snippetWorkwithGlobalOptionSets3>
                    Console.WriteLine("Referring picklist attribute created.");
                    #endregion How to create a picklist linked to the global option set

                    #region How to update a global option set
                    //<snippetWorkwithGlobalOptionSets4>
                    // Use UpdateOptionSetRequest to update the basic information of an option
                    // set. Updating option set values requires different messages (see below).
                    var updateOptionSetRequest = new UpdateOptionSetRequest
                    {
                        OptionSet = new OptionSetMetadata
                        {
                            DisplayName = new Label("Updated Option Set", _languageCode),
                            Name        = _globalOptionSetName,
                            IsGlobal    = true
                        }
                    };

                    service.Execute(updateOptionSetRequest);

                    //Publish the OptionSet
                    var pxReq1 = new PublishXmlRequest {
                        ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName)
                    };
                    service.Execute(pxReq1);
                    //</snippetWorkwithGlobalOptionSets4>
                    Console.WriteLine("Option Set display name changed.");
                    #endregion How to update a global option set properties

                    #region How to insert a new option item in a global option set
                    //<snippetWorkwithGlobalOptionSets5>
                    // Use InsertOptionValueRequest to insert a new option into a
                    // global option set.
                    InsertOptionValueRequest insertOptionValueRequest =
                        new InsertOptionValueRequest
                    {
                        OptionSetName = _globalOptionSetName,
                        Label         = new Label("New Picklist Label", _languageCode)
                    };

                    // Execute the request and store the newly inserted option value
                    // for cleanup, used in the later part of this sample.
                    _insertedOptionValue = ((InsertOptionValueResponse)service.Execute(
                                                insertOptionValueRequest)).NewOptionValue;

                    //Publish the OptionSet
                    PublishXmlRequest pxReq2 = new PublishXmlRequest {
                        ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName)
                    };
                    service.Execute(pxReq2);
                    //</snippetWorkwithGlobalOptionSets5>
                    Console.WriteLine("Created {0} with the value of {1}.",
                                      insertOptionValueRequest.Label.LocalizedLabels[0].Label,
                                      _insertedOptionValue);
                    #endregion How to insert a new option item in a global option set

                    #region How to retrieve a global option set by it's name
                    //<snippetWorkwithGlobalOptionSets6>
                    // Use the RetrieveOptionSetRequest message to retrieve
                    // a global option set by it's name.
                    RetrieveOptionSetRequest retrieveOptionSetRequest =
                        new RetrieveOptionSetRequest
                    {
                        Name = _globalOptionSetName
                    };

                    // Execute the request.
                    RetrieveOptionSetResponse retrieveOptionSetResponse =
                        (RetrieveOptionSetResponse)service.Execute(
                            retrieveOptionSetRequest);

                    Console.WriteLine("Retrieved {0}.",
                                      retrieveOptionSetRequest.Name);

                    // Access the retrieved OptionSetMetadata.
                    OptionSetMetadata retrievedOptionSetMetadata =
                        (OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata;

                    // Get the current options list for the retrieved attribute.
                    OptionMetadata[] optionList =
                        retrievedOptionSetMetadata.Options.ToArray();
                    //</snippetWorkwithGlobalOptionSets6>
                    #endregion How to retrieve a global option set by it's name

                    #region How to update an option item in a picklist
                    //<snippetWorkwithGlobalOptionSets7>
                    // In order to change labels on option set values (or delete) option set
                    // values, you must use UpdateOptionValueRequest
                    // (or DeleteOptionValueRequest).
                    UpdateOptionValueRequest updateOptionValueRequest =
                        new UpdateOptionValueRequest
                    {
                        OptionSetName = _globalOptionSetName,
                        // Update the second option value.
                        Value = optionList[1].Value.Value,
                        Label = new Label("Updated Option 1", _languageCode)
                    };

                    service.Execute(updateOptionValueRequest);

                    //Publish the OptionSet
                    PublishXmlRequest pxReq3 = new PublishXmlRequest {
                        ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName)
                    };
                    service.Execute(pxReq3);



                    //</snippetWorkwithGlobalOptionSets7>
                    Console.WriteLine("Option Set option label changed.");
                    #endregion How to update an option item in a picklist

                    #region How to change the order of options of a global option set
                    //<snippetWorkwithGlobalOptionSets8>
                    // Change the order of the original option's list.
                    // Use the OrderBy (OrderByDescending) linq function to sort options in
                    // ascending (descending) order according to label text.
                    // For ascending order use this:
                    var updateOptionList =
                        optionList.OrderBy(x => x.Label.LocalizedLabels[0].Label).ToList();

                    // For descending order use this:
                    // var updateOptionList =
                    //      optionList.OrderByDescending(
                    //      x => x.Label.LocalizedLabels[0].Label).ToList();

                    // Create the request.
                    OrderOptionRequest orderOptionRequest = new OrderOptionRequest
                    {
                        // Set the properties for the request.
                        OptionSetName = _globalOptionSetName,
                        // Set the changed order using Select linq function
                        // to get only values in an array from the changed option list.
                        Values = updateOptionList.Select(x => x.Value.Value).ToArray()
                    };

                    // Execute the request
                    service.Execute(orderOptionRequest);

                    //Publish the OptionSet
                    PublishXmlRequest pxReq4 = new PublishXmlRequest {
                        ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName)
                    };
                    service.Execute(pxReq4);
                    //</snippetWorkwithGlobalOptionSets8>
                    Console.WriteLine("Option Set option order changed");
                    #endregion How to change the order of options of a global option set

                    #region How to retrieve all global option sets
                    //<snippetWorkwithGlobalOptionSets9>
                    // Use RetrieveAllOptionSetsRequest to retrieve all global option sets.
                    // Create the request.
                    RetrieveAllOptionSetsRequest retrieveAllOptionSetsRequest =
                        new RetrieveAllOptionSetsRequest();

                    // Execute the request
                    RetrieveAllOptionSetsResponse retrieveAllOptionSetsResponse =
                        (RetrieveAllOptionSetsResponse)service.Execute(
                            retrieveAllOptionSetsRequest);

                    // Now you can use RetrieveAllOptionSetsResponse.OptionSetMetadata property to
                    // work with all retrieved option sets.
                    if (retrieveAllOptionSetsResponse.OptionSetMetadata.Count() > 0)
                    {
                        Console.WriteLine("All the global option sets retrieved as below:");
                        int count = 1;
                        foreach (OptionSetMetadataBase optionSetMetadata in
                                 retrieveAllOptionSetsResponse.OptionSetMetadata)
                        {
                            Console.WriteLine("{0} {1}", count++,
                                              (optionSetMetadata.DisplayName.LocalizedLabels.Count > 0) ? optionSetMetadata.DisplayName.LocalizedLabels[0].Label : String.Empty);
                        }
                    }
                    #endregion Demonstrate

                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Esempio n. 35
0
        static void Main(string[] args)
        {
            var _languageCode = 1033;

            CrmServiceClient connection = new CrmServiceClient(ConfigurationManager.ConnectionStrings["crm"].ConnectionString);
            var service = (IOrganizationService)connection.OrganizationWebProxyClient ?? (IOrganizationService)connection.OrganizationServiceProxy;


            //To reduce the number of classes generated to those which are most useful,
            // the following entities will be excluded. If necessary, you can comment out
            // items from this array so that class files will be generated for the entity
            String[] excludedEntities = {
                                  "ApplicationFile",
                                  "AsyncOperation",
                                  "AttributeMap",
                                  "AuthorizationServer",
                                  "BulkDeleteFailure",
                                  "BulkDeleteOperation",
                                  "BulkOperation",
                                  "BulkOperationLog",
                                  "BusinessProcessFlowInstance",
                                  "BusinessUnitMap",
                                  "BusinessUnitNewsArticle",
                                  "ChildIncidentCount",
                                  "ClientUpdate",
                                  "ColumnMapping",
                                  "Commitment",
                                  "ComplexControl",
                                  "ConvertRule",
                                  "ConvertRuleItem",
                                  "Dependency",
                                  "DependencyFeature",
                                  "DependencyNode",
                                  "DisplayString",
                                  "DisplayStringMap",
                                  "DocumentIndex",
                                  "DuplicateRecord",
                                  "DuplicateRule",
                                  "DuplicateRuleCondition",
                                  "EmailHash",
                                  "EmailSearch",
                                  "EmailServerProfile",
                                  "EntityMap",
                                  "ExchangeSyncIdMapping",
                                  "FieldPermission",
                                  "FieldSecurityProfile",
                                  "FilterTemplate",
                                  "FixedMonthlyFiscalCalendar",
                                  "ImageDescriptor",
                                  "Import",
                                  "ImportData",
                                  "ImportEntityMapping",
                                  "ImportFile",
                                  "ImportJob",
                                  "ImportLog",
                                  "ImportMap",
                                  "IntegrationStatus",
                                  "InternalAddress",
                                  "InterProcessLock",
                                  "InvalidDependency",
                                  "IsvConfig",
                                  "License",
                                  "LookUpMapping",
                                  "Mailbox",
                                  "MailboxStatistics",
                                  "MetadataDifference",
                                  "MultiEntitySearch",
                                  "MultiEntitySearchEntities",
                                  "Notification",
                                  "OrganizationStatistic",
                                  "OrganizationUI",
                                  "OwnerMapping",
                                  "PartnerApplication",
                                  "PickListMapping",
                                  "PluginAssembly",
                                  "PluginType",
                                  "PluginTypeStatistic",
                                  "PrincipalObjectAccess",
                                  "PrincipalObjectAccessReadSnapshot",
                                  "PrincipalObjectAttributeAccess",
                                  "Privilege",
                                  "PrivilegeObjectTypeCodes",
                                  "ProcessSession",
                                  "ProcessStage",
                                  "ProcessTrigger",
                                  "Publisher",
                                  "PublisherAddress",
                                  "RecordCountSnapshot",
                                  "RelationshipRole",
                                  "RelationshipRoleMap",
                                  "ReplicationBacklog",
                                  "Report",
                                  "ReportCategory",
                                  "ReportEntity",
                                  "ReportLink",
                                  "ReportVisibility",
                                  "RibbonCommand",
                                  "RibbonContextGroup",
                                  "RibbonCustomization",
                                  "RibbonDiff",
                                  "RibbonRule",
                                  "RibbonTabToCommandMap",
                                  "RoutingRule",
                                  "RoutingRuleItem",
                                  "SalesProcessInstance",
                                  "SdkMessage",
                                  "SdkMessageFilter",
                                  "SdkMessagePair",
                                  "SdkMessageProcessingStep",
                                  "SdkMessageProcessingStepImage",
                                  "SdkMessageProcessingStepSecureConfig",
                                  "SdkMessageRequest",
                                  "SdkMessageRequestField",
                                  "SdkMessageResponse",
                                  "SdkMessageResponseField",
                                  "ServiceEndpoint",
                                  "SiteMap",
                                  "SLA",
                                  "SLAItem",
                                  "Solution",
                                  "SolutionComponent",
                                  "SqlEncryptionAudit",
                                  "StatusMap",
                                  "StringMap",
                                  "Subscription",
                                  "SubscriptionClients",
                                  "SubscriptionSyncInfo",
                                  "SubscriptionTrackingDeletedObject",
                                  "SystemApplicationMetadata",
                                  "SystemForm",
                                  "SystemUserBusinessUnitEntityMap",
                                  "SystemUserPrincipals",
                                  "TraceAssociation",
                                  "TraceLog",
                                  "TraceRegarding",
                                  "TransformationMapping",
                                  "TransformationParameterMapping",
                                  "UnresolvedAddress",
                                  "UserApplicationMetadata",
                                  "UserEntityInstanceData",
                                  "UserEntityUISettings",
                                  "WebWizard",
                                  "WizardAccessPrivilege",
                                  "WizardPage",
                                  "WorkflowWaitSubscription"
                                 };
            MetadataFilterExpression EntityFilter = new MetadataFilterExpression(LogicalOperator.And);
            // No classes for intersect entities
            EntityFilter.Conditions.Add(new MetadataConditionExpression("IsIntersect", MetadataConditionOperator.Equals, false));
            // Do not retrieve excluded entities
            EntityFilter.Conditions.Add(new MetadataConditionExpression("SchemaName", MetadataConditionOperator.NotIn, excludedEntities));


            //A properties expression to limit the properties to be included with entities
            MetadataPropertiesExpression EntityProperties = new MetadataPropertiesExpression()
            {
                AllProperties = false
            };
            EntityProperties.PropertyNames.AddRange(new string[] {
                        "Attributes",
                        "Description",
                        "DisplayName",
                        "OneToManyRelationships",
                        "SchemaName" });


            MetadataConditionExpression[] attributesToReturn = new MetadataConditionExpression[] { 
                 //No virtual attributes
                 new MetadataConditionExpression("AttributeType", MetadataConditionOperator.NotEquals, AttributeTypeCode.Virtual),
                 // No child attributes
                 new MetadataConditionExpression("AttributeOf", MetadataConditionOperator.Equals, null)
                 };


            MetadataFilterExpression AttributeFilter = new MetadataFilterExpression(LogicalOperator.And);
            AttributeFilter.Conditions.AddRange(attributesToReturn);


            MetadataPropertiesExpression AttributeProperties = new MetadataPropertiesExpression() { AllProperties = false };
            AttributeProperties.PropertyNames.Add("AttributeTypeName");
            AttributeProperties.PropertyNames.Add("MaxLength");
            AttributeProperties.PropertyNames.Add("OptionSet");
            AttributeProperties.PropertyNames.Add("Description");
            AttributeProperties.PropertyNames.Add("DisplayName");
            AttributeProperties.PropertyNames.Add("RequiredLevel");
            AttributeProperties.PropertyNames.Add("SchemaName");
            AttributeProperties.PropertyNames.Add("Targets");
            AttributeProperties.PropertyNames.Add("IsValidForCreate");
            AttributeProperties.PropertyNames.Add("IsValidForRead");
            AttributeProperties.PropertyNames.Add("IsValidForUpdate");


            MetadataFilterExpression relationshipFilter = new MetadataFilterExpression(LogicalOperator.And);

            MetadataPropertiesExpression relationshipProperties = new MetadataPropertiesExpression() { AllProperties = false };
            relationshipProperties.PropertyNames.Add("SchemaName");
            relationshipProperties.PropertyNames.Add("ReferencingEntity");
            relationshipProperties.PropertyNames.Add("ReferencingAttribute");



            //A label query expression to limit the labels returned to only those for the user's preferred language
            LabelQueryExpression labelQuery = new LabelQueryExpression();
            //labelQuery.FilterLanguages.Add(_languageCode);


            //An entity query expression to combine the filter expressions and property expressions for the query.
            EntityQueryExpression entityQueryExpression = new EntityQueryExpression()
            {

                Criteria = EntityFilter,
                Properties = EntityProperties,
                AttributeQuery = new AttributeQueryExpression()
                {
                    Criteria = AttributeFilter,
                    Properties = AttributeProperties
                },
                RelationshipQuery = new RelationshipQueryExpression()
                {
                    Criteria = relationshipFilter,
                    Properties = relationshipProperties
                },
                LabelQuery = labelQuery

            };

            RetrieveMetadataChangesRequest rmdcr = new RetrieveMetadataChangesRequest()
            {
                Query = entityQueryExpression
            };
            RetrieveMetadataChangesResponse resp = (RetrieveMetadataChangesResponse)service.Execute(rmdcr);

            EntityMetadataCollection entities = resp.EntityMetadata;

            foreach (EntityMetadata entity in entities)
            {
                writeEntityTSFile(entity);
            }
            Console.WriteLine("Done!");
        }
        [STAThread] // Added to support UX
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    #region Sample Code
                    #region Set up
                    SetUpSample(service);
                    #endregion Set up
                    #region Demonstrate
                    // Prompt user to install/uninstall sample data.
                    Console.WriteLine("Would you like to:");
                    Console.WriteLine("1) Install sample data for CDS?");

                    Console.WriteLine("2) Uninstall sample data for CDS?");
                    Console.Write("Press [1] to Install, [2] to Uninstall: ");
                    String answer = Console.ReadLine();

                    // Update the sample data based on the user's response.
                    switch (answer)
                    {
                    case "1":
                        Console.WriteLine("Installing sample data...");
                        InstallSampleDataRequest request =
                            new InstallSampleDataRequest();
                        InstallSampleDataResponse response =
                            (InstallSampleDataResponse)service.Execute(request);
                        Console.WriteLine("Sample data successfully installed.");
                        break;

                    case "2":
                        Console.WriteLine("Uninstalling sample data...");
                        UninstallSampleDataRequest request2 =
                            new UninstallSampleDataRequest();
                        UninstallSampleDataResponse response2 =
                            (UninstallSampleDataResponse)service.Execute(request2);
                        Console.WriteLine("Sample data successfully uninstalled.");
                        break;

                    default:
                        Console.WriteLine("Neither option was selected. No changes have been made to your records.");
                        break;
                    }
                }
                #endregion Demonstrate
                #endregion Sample Code
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Esempio n. 37
0
        /// <summary>
        /// This raises and processes Success
        /// </summary>
        private void ProcessSuccess()
        {
            resetUiFlag = true;
            bIsConnectedComplete = true;
            CrmSvc = mgr.CrmSvc;
            CrmLoginCtrl.GoBackToLogin();
            Dispatcher.Invoke(DispatcherPriority.Normal,
               new System.Action(() =>
               {
                   this.Title = "Notification from Parent";
                   CrmLoginCtrl.IsEnabled = true;
               }
                ));

            // Notify Caller that we are done with success. 
            if (ConnectionToCrmCompleted != null)
                ConnectionToCrmCompleted(this, null);

            resetUiFlag = false;
        }
Esempio n. 38
0
        [STAThread] // Added to support UX
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    #region Sample Code
                    //////////////////////////////////////////////
                    #region Set up
                    SetUpSample(service);
                    #endregion Set up
                    #region Demonstrate

                    // This query retrieves all connection roles that have this role
                    // listed as a reciprocal role.
                    QueryExpression query = new QueryExpression
                    {
                        EntityName   = ConnectionRole.EntityLogicalName,
                        ColumnSet    = new ColumnSet("connectionroleid"),
                        LinkEntities =
                        {
                            new LinkEntity
                            {
                                JoinOperator          = JoinOperator.Inner,
                                LinkFromEntityName    = ConnectionRole.EntityLogicalName,
                                LinkFromAttributeName = "connectionroleid",
                                LinkToEntityName      = "connectionroleassociation",
                                LinkToAttributeName   = "connectionroleid",
                                LinkCriteria          = new FilterExpression
                                {
                                    FilterOperator = LogicalOperator.And,
                                    Conditions     =
                                    {
                                        new ConditionExpression
                                        {
                                            AttributeName = "associatedconnectionroleid",
                                            Operator      = ConditionOperator.Equal,
                                            Values        = { _reciprocalConnectionRoleId }
                                        }
                                    }
                                }
                            }
                        }
                    };

                    EntityCollection results = service.RetrieveMultiple(query);

                    // TODO: Here you would perform some operation on the retrieved
                    // roles.

                    Console.WriteLine("Retrieved {0} connectionrole instance.", results.Entities.Count);


                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                #endregion Demonstrate
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            #endregion Sample Code
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
        private void Connect()
        {
            visitedPath.Add(pnlWaiting.Name);

            var bw = new BackgroundWorker();
            bw.DoWork += (bwSender, evt) =>
            {
                var detail = (ConnectionDetail)evt.Argument;
                evt.Result = detail.GetCrmServiceClient(true);
            };
            bw.RunWorkerCompleted += (bwSender, evt) =>
            {
                if (evt.Error != null)
                {
                    lblDescription.Text = Resources.ConnectionWizard_ErrorHeaderDescription;

                    lblError.Text = evt.Error.Message;
                    DisplayPanel(pnlError, null);

                    return;
                }

                CrmServiceClient crmSvc = (CrmServiceClient)evt.Result;

                if (!crmSvc.IsReady)
                {
                    lblDescription.Text = Resources.ConnectionWizard_ErrorHeaderDescription;

                    lblError.Text = crmSvc.LastCrmError;
                    DisplayPanel(pnlError, null);

                    return;
                }

                lblDescription.Text = Resources.ConnectionWizard_SuccessHeaderDescription;

                DisplayPanel(pnlConnected, btnFinish);
                txtConnectionName.Focus();

                serviceClient = crmSvc;
            };
            bw.RunWorkerAsync(updatedDetail);
        }
        [STAThread] // Required to support the interactive login experience
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    // Create any entity records that the demonstration code requires
                    SetUpSample(service);

                    #region Demonstrate
                    // Retrieve a user.
                    SystemUser user = service.Retrieve(SystemUser.EntityLogicalName,
                                                       _userId, new ColumnSet(new String [] { "systemuserid", "firstname", "lastname" })).ToEntity <SystemUser>();

                    if (user != null)
                    {
                        Console.WriteLine("'{1} {0}' account record was retrieved.", user.LastName, user.FirstName);
                        SetStateRequest request = new SetStateRequest()
                        {
                            EntityMoniker = user.ToEntityReference(),

                            // Sets the user to disabled.
                            State = new OptionSetValue(1),
                            // Required by request but always valued at -1 in this context.
                            Status = new OptionSetValue(-1)

                                     // See DeleteRequiredRecords() to find out how to enable a user.
                        };

                        service.Execute(request);

                        Console.WriteLine("The specified system user account is now disabled.");
                    }
                    #endregion Demonstrate

                    DeleteRequiredRecords(service, true);
                }
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Microsoft Dataverse";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }