public Context Generate(IOrganizationService service, Guid selectedUserId)
        {
            var xrmContext = new XrmServiceContext(service);
            var userRoles  = xrmContext.SystemUserRolesSet
                             .Where(e => e.SystemUserId == selectedUserId).Select(e => e.RoleId.GetValueOrDefault()).ToList();
            var userSettings = xrmContext.UserSettingsSet
                               .Where(e => e.SystemUserIdId == selectedUserId).Select(e => e).FirstOrDefault();
            var user           = xrmContext.UserSet.Where(e => e.UserId == selectedUserId).Select(e => e).FirstOrDefault();
            var organisation   = xrmContext.OrganizationSet.Select(e => e).FirstOrDefault();
            var theme          = xrmContext.ThemeSet.Where(e => e.DefaultTheme == true).Select(e => e).FirstOrDefault();
            var versionRequest = new RetrieveVersionRequest();
            var version        = ((RetrieveVersionResponse)service.Execute(versionRequest)).Version;

            return
                (new Context
            {
                UserId = user?.UserId ?? Guid.Empty,
                Username = user?.UserName,
                UserFullName = user?.FullName,
                IsGuidedHelpEnabled = userSettings?.EnableDefaultGuidedHelp ?? false,
                UserLanguageCode = userSettings?.UILanguageId ?? 1033,
                TimeZoneBias = userSettings?.TimeZoneBias ?? 0,
                UserRoles = userRoles,
                OrganisationUrl = organisation?.ExternalBaseURL,
                IsAutoSaveEnabled = organisation?.AutoSaveEnabled ?? false,
                OrgLanguageCode = organisation?.Language ?? 1033,
                OrganisationName = organisation?.OrganizationName,
                ThemeName = theme?.ThemeName,
                CrmVersion = version
            });
        }
Пример #2
0
        public CrmConnectionInfo GetConnectionInfo(CrmDbConnection connection)
        {
            var connInfo = _Cache.GetOrAdd(connection.ConnectionString, f =>
            {

                WhoAmIRequest whoRequest = new WhoAmIRequest();
                WhoAmIResponse whoResponse = (WhoAmIResponse)connection.OrganizationService.Execute(whoRequest);

                var info = new CrmConnectionInfo();
                if (whoResponse != null)
                {
                    info.OrganisationId = whoResponse.OrganizationId;
                    info.UserId = whoResponse.UserId;
                    info.BusinessUnitId = whoResponse.BusinessUnitId;
                }

                var orgEntity = connection.OrganizationService.Retrieve("organization", info.OrganisationId, new ColumnSet("name"));
                if (orgEntity != null)
                {
                    info.OrganisationName = (string)orgEntity["name"];
                }

                var versionReq = new RetrieveVersionRequest();
                var versionResponse = (RetrieveVersionResponse)connection.OrganizationService.Execute(versionReq);
                if (versionResponse != null)
                {
                    info.ServerVersion = versionResponse.Version;
                }

                return info;

            });

            return connInfo;
        }
Пример #3
0
        private static string GetVersion(IOrganizationService service)
        {
            var request  = new RetrieveVersionRequest();
            var response = (RetrieveVersionResponse)service.Execute(request);

            return(response.Version);
        }
Пример #4
0
        public CrmConnectionInfo GetConnectionInfo(CrmDbConnection connection)
        {
            var connInfo = _Cache.GetOrAdd(connection.ConnectionString, f =>
            {
                WhoAmIRequest whoRequest   = new WhoAmIRequest();
                WhoAmIResponse whoResponse = (WhoAmIResponse)connection.OrganizationService.Execute(whoRequest);

                var info = new CrmConnectionInfo();
                if (whoResponse != null)
                {
                    info.OrganisationId = whoResponse.OrganizationId;
                    info.UserId         = whoResponse.UserId;
                    info.BusinessUnitId = whoResponse.BusinessUnitId;
                }

                var orgEntity = connection.OrganizationService.Retrieve("organization", info.OrganisationId, new ColumnSet("name"));
                if (orgEntity != null)
                {
                    info.OrganisationName = (string)orgEntity["name"];
                }

                var versionReq      = new RetrieveVersionRequest();
                var versionResponse = (RetrieveVersionResponse)connection.OrganizationService.Execute(versionReq);
                if (versionResponse != null)
                {
                    info.ServerVersion = versionResponse.Version;
                }

                return(info);
            });

            return(connInfo);
        }
Пример #5
0
        public Version RetrieveVersion()
        {
            var request  = new RetrieveVersionRequest();
            var response = (RetrieveVersionResponse)service.Execute(request);

            return(Version.Parse(response.Version));
        }
Пример #6
0
        private RetrieveVersionResponse ConnectToCrm(string connectionString)
        {
            try
            {
                CrmConnection connection = CrmConnection.Parse(connectionString);
                using (OrganizationService orgService = new OrganizationService(connection))
                {
                    WhoAmIRequest  wRequest  = new WhoAmIRequest();
                    WhoAmIResponse wResponse = (WhoAmIResponse)orgService.Execute(wRequest);
                    _logger.WriteToOutputWindow("Connected To CRM Organization: " + wResponse.OrganizationId, Logger.MessageType.Info);

                    OrgId = wResponse.OrganizationId.ToString();

                    RetrieveVersionRequest  vRequest  = new RetrieveVersionRequest();
                    RetrieveVersionResponse vResponse = (RetrieveVersionResponse)orgService.Execute(vRequest);
                    _logger.WriteToOutputWindow("Version: " + vResponse.Version, Logger.MessageType.Info);

                    return(vResponse);
                }
            }
            catch (FaultException <OrganizationServiceFault> crmEx)
            {
                _logger.WriteToOutputWindow("Error Connecting To CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error);
                return(null);
            }
            catch (Exception ex)
            {
                _logger.WriteToOutputWindow("Error Connecting To CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error);
                return(null);
            }
        }
        //<snippetCRUDOperations1>
        /// <summary>
        /// This method performs entity create, retrieve, and update operations.
        /// The delete operation is handled in the DeleteRequiredrecords() method.
        /// </summary>
        /// <param name="serviceProxy">An established connection to the Organization web service.</param>
        /// <param name="records">A collection of entity records created by this sample.</param>
        public void Run(OrganizationServiceProxy serviceProxy, EntityReferenceCollection records)
        {
            // Enable early-bound entity types. This enables use of IntelliSense in Visual Studio
            // and avoids spelling errors in attribute names when using the Entity property bag.
            serviceProxy.EnableProxyTypes();

            // Here we will use the interface instead of the proxy object.
            IOrganizationService service = (IOrganizationService)serviceProxy;

            // Display information about the logged on user.
            Guid userid = ((WhoAmIResponse)service.Execute(new WhoAmIRequest())).UserId;
            SystemUser systemUser = (SystemUser)service.Retrieve("systemuser", userid, 
                new ColumnSet(new string[] {"firstname", "lastname"}));
            Console.WriteLine("Logged on user is {0} {1}.", systemUser.FirstName, systemUser.LastName);
 
            // Retrieve the version of Microsoft Dynamics CRM.
            RetrieveVersionRequest versionRequest = new RetrieveVersionRequest();
            RetrieveVersionResponse versionResponse =
                (RetrieveVersionResponse)service.Execute(versionRequest);
            Console.WriteLine("Microsoft Dynamics CRM version {0}.", versionResponse.Version);

            //<snippetCRUDOperations2>
            // Instantiate an account object. Note the use of the option set enumerations defined
            // in OptionSets.cs.
            Account account = new Account { Name = "Fourth Coffee" };
            account.AccountCategoryCode = new OptionSetValue((int)AccountAccountCategoryCode.PreferredCustomer);
            account.CustomerTypeCode = new OptionSetValue((int)AccountCustomerTypeCode.Investor);

            // Create an account record named Fourth Coffee.
            // Save the record reference so we can delete it during cleanup later.
            Guid accountId = service.Create(account);
            //</snippetCRUDOperations2>
            records.Add(new EntityReference(Account.EntityLogicalName, accountId));
            Console.Write("{0} {1} created, ", account.LogicalName, account.Name);

            // Retrieve the account containing several of its attributes. This results in
            // better performance compared to retrieving all attributes.
            ColumnSet cols = new ColumnSet(
                new String[] { "name", "address1_postalcode", "lastusedincampaign" });

            Account retrievedAccount = (Account)service.Retrieve("account", accountId, cols);
            Console.Write("retrieved, ");

            // Update the postal code attribute.
            retrievedAccount.Address1_PostalCode = "98052";

            // There is no address 2 postal code needed.
            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.WriteLine("and updated.");
        }
Пример #8
0
        public void ShowCRMVersion()
        {
            RetrieveVersionRequest  versionRequest  = new RetrieveVersionRequest();
            RetrieveVersionResponse versionResponse =
                (RetrieveVersionResponse)CRMOrganizationService.Execute(versionRequest);

            Logger(String.Format("Microsoft Dynamics CRM version {0}.", versionResponse.Version));
        }
        private bool Is2011(IOrganizationService service)
        {
            //Check if 2011
            RetrieveVersionRequest request  = new RetrieveVersionRequest();
            OrganizationResponse   response = service.Execute(request);

            return(response.Results["Version"].ToString().StartsWith("5"));
        }
Пример #10
0
        /// <summary>
        /// Gets the version.
        /// </summary>
        /// <returns></returns>
        public Version GetVersion()
        {
            var request  = new RetrieveVersionRequest();
            var response = (RetrieveVersionResponse)_service.Execute(request);
            var version  = new Version(response.Version);

            return(version);
        }
Пример #11
0
        public static void Main(IOrganizationService service)
        {
            var request = new RetrieveVersionRequest();
            var response = (RetrieveVersionResponse)service.Execute(request);
            var version = new Version(response.Version);

            Console.WriteLine("CRM Version is: {0}", version);
        }
Пример #12
0
        private static void DisplayDynamicsCrmVersion(IOrganizationService organizationService)
        {
            // Retrieve the version of Microsoft Dynamics CRM.
            RetrieveVersionRequest  versionRequest  = new RetrieveVersionRequest();
            RetrieveVersionResponse versionResponse =
                (RetrieveVersionResponse)organizationService.Execute(versionRequest);

            Console.WriteLine("Microsoft Dynamics CRM version {0}.", versionResponse.Version);
        }
Пример #13
0
        /// <summary>
        /// Connects to a Crm server
        /// </summary>
        /// <param name="parameters">List of parameters</param>
        /// <returns>An exception or an IOrganizationService</returns>
        private object Connect(List <object> parameters)
        {
            WebRequest.DefaultWebProxy = WebRequest.GetSystemWebProxy();

            var detail = (ConnectionDetail)parameters[0];

            SendStepChange("Creating Organization service proxy...");

            // Connecting to Crm server
            try
            {
                var service = (OrganizationService)detail.GetOrganizationService();

                ((OrganizationServiceProxy)service.InnerService).SdkClientVersion = detail.OrganizationVersion;

                TestConnection(service);

                // If the current connection detail does not contain the web
                // application url, we search for it
                if (string.IsNullOrEmpty(detail.WebApplicationUrl))
                {
                    var discoService = (DiscoveryService)detail.GetDiscoveryService();
                    var result       = (RetrieveOrganizationResponse)discoService.Execute(new RetrieveOrganizationRequest {
                        UniqueName = detail.Organization
                    });
                    detail.WebApplicationUrl = result.Detail.Endpoints[EndpointType.WebApplication];
                }

                // We search for organization version
                var vRequest  = new RetrieveVersionRequest();
                var vResponse = (RetrieveVersionResponse)service.Execute(vRequest);

                detail.OrganizationVersion = vResponse.Version;

                var currentConnection = ConnectionsList.Connections.FirstOrDefault(x => x.ConnectionId == detail.ConnectionId);
                if (currentConnection != null)
                {
                    currentConnection.WebApplicationUrl   = detail.WebApplicationUrl;
                    currentConnection.OrganizationVersion = vResponse.Version;
                    currentConnection.SavePassword        = detail.SavePassword;
                    detail.CopyPasswordTo(currentConnection);
                }

                detail.LastUsedOn = DateTime.Now;

                SaveConnectionsFile();

                return(service);
            }
            catch (Exception error)
            {
                return(error);
            }
        }
Пример #14
0
        private bool IsSupportWebResourceDependency()
        {
            var request  = new RetrieveVersionRequest();
            var response = (RetrieveVersionResponse)CrmServiceClient.Execute(request);
            var version  = new Version(response.Version);

            if (version >= new Version("9.0"))
            {
                return(true);
            }
            return(false);
        }
Пример #15
0
        public void getEntityMetaData()
        {
            IOrganizationService service = CRMHelper.ConnectToMSCRM();

            RetrieveVersionRequest  versionReq = new RetrieveVersionRequest();
            RetrieveVersionResponse resp       = (RetrieveVersionResponse)service.Execute(versionReq);
            //assigns the version to a string
            string VersionNumber = resp.Version;

            bool isKeyCompatibleVersion = isCompatibleVersion(VersionNumber);

            MetadataFilterExpression EntityFilter = new MetadataFilterExpression(LogicalOperator.And);

            EntityFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, "contact"));

            MetadataPropertiesExpression EntityProperties = new MetadataPropertiesExpression()
            {
                AllProperties = false
            };

            EntityProperties.PropertyNames.AddRange(new string[] { "Attributes", "OneToManyRelationships", "LogicalName", "DisplayName", "PrimaryIdAttribute", "PrimaryNameAttribute" });
            if (isKeyCompatibleVersion)
            {
                EntityProperties.PropertyNames.Add("Keys");
            }


            MetadataPropertiesExpression AttributeProperties = new MetadataPropertiesExpression()
            {
                AllProperties = false
            };

            AttributeProperties.PropertyNames.AddRange("AttributeType", "LogicalName", "DisplayName", "SchemaName", "AttributeType", "IsPrimaryName", "IsValidForUpdate", "OptionSet");

            EntityQueryExpression entityQueryExpression = new EntityQueryExpression()
            {
                Criteria       = EntityFilter,
                Properties     = EntityProperties,
                AttributeQuery = new AttributeQueryExpression()
                {
                    Properties = AttributeProperties
                }//,
                 //RelationshipQuery = new RelationshipQueryExpression() { Properties = new MetadataPropertiesExpression() {  AllProperties = true} }
            };

            RetrieveMetadataChangesRequest req = new RetrieveMetadataChangesRequest()
            {
                Query = entityQueryExpression
            };

            var response = (RetrieveMetadataChangesResponse)service.Execute(req);
        }
Пример #16
0
        public Version GetCrmVersion()
        {
            if (Service is CrmServiceClient client)
            {
                return(client.ConnectedOrgVersion);
            }
            else
            {
                var request  = new RetrieveVersionRequest();
                var response = (RetrieveVersionResponse)Service.Execute(request);

                return(new Version(response.Version));
            }
        }
Пример #17
0
        /// <summary>
        /// Checks the current CRM version.
        /// If it is anything lower than 7.1.0.0, prompt to upgrade.
        /// </summary>
        private bool CheckCRMVersion()
        {
            RetrieveVersionRequest  crmVersionReq  = new RetrieveVersionRequest();
            RetrieveVersionResponse crmVersionResp = (RetrieveVersionResponse)_serviceProxy.Execute(crmVersionReq);

            if (String.CompareOrdinal("7.1.0.0", crmVersionResp.Version) < 0)
            {
                return(true);
            }
            else
            {
                Console.WriteLine("This sample cannot be run against the current version of CRM.");
                Console.WriteLine("Upgrade your CRM instance to the latest version to run this sample.");
                return(false);
            }
        }
Пример #18
0
        public void Experiment_For_Crm_Version_Request()
        {
            var connectionString = ConfigurationManager.ConnectionStrings["CrmOrganisation"];
            var serviceProvider  = new CrmServiceProvider(new ExplicitConnectionStringProviderWithFallbackToConfig()
            {
                OrganisationServiceConnectionString = connectionString.ConnectionString
            },
                                                          new CrmClientCredentialsProvider());

            var orgService = serviceProvider.GetOrganisationService();

            using (orgService as IDisposable)
            {
                var req  = new RetrieveVersionRequest();
                var resp = (RetrieveVersionResponse)orgService.Execute(req);
                //assigns the version to a string
                string versionNumber = resp.Version;
                Console.WriteLine(versionNumber);
            }
        }
        public Context Generate(IOrganizationService service, Guid selectedUserId)
        {
            var xrmContext = new XrmServiceContext(service);

            var userRoles = xrmContext.CreateQuery(SystemUserRoles.EntityLogicalName)
                            .Where(e => e.GetAttributeValue <EntityReference>(SystemUserRoles.Fields.SystemUserId).Id == selectedUserId)
                            .Select(e => e.GetAttributeValue <Guid?>(SystemUserRoles.Fields.RoleId).GetValueOrDefault()).ToList();
            var userSettings = xrmContext.CreateQuery(UserSettings.EntityLogicalName)
                               .Where(e => e.GetAttributeValue <EntityReference>(UserSettings.Fields.SystemUserIdId).Id == selectedUserId)
                               .Select(e => e).FirstOrDefault();
            var user = xrmContext.CreateQuery(User.EntityLogicalName)
                       .Where(e => e.GetAttributeValue <Guid?>(SystemUserRoles.Fields.SystemUserId) == selectedUserId)
                       .Select(e => e).FirstOrDefault();
            var organisation = xrmContext.CreateQuery(Organization.EntityLogicalName)
                               .Select(e => e).FirstOrDefault();
            var theme = xrmContext.CreateQuery(Theme.EntityLogicalName)
                        .Where(e => e.GetAttributeValue <bool?>(Theme.Fields.DefaultTheme) == true)
                        .Select(e => e).FirstOrDefault();

            var versionRequest = new RetrieveVersionRequest();
            var version        = ((RetrieveVersionResponse)service.Execute(versionRequest)).Version;

            return
                (new Context
            {
                UserId = user?.GetAttributeValue <Guid?>(User.Fields.UserId) ?? Guid.Empty,
                Username = user?.GetAttributeValue <string>(User.Fields.UserName),
                UserFullName = user?.GetAttributeValue <string>(User.Fields.FullName),
                IsGuidedHelpEnabled = userSettings?
                                      .GetAttributeValue <bool?>(UserSettings.Fields.EnableDefaultGuidedHelp) ?? false,
                UserLanguageCode = userSettings?.GetAttributeValue <int?>(UserSettings.Fields.UILanguageId) ?? 1033,
                TimeZoneBias = userSettings?.GetAttributeValue <int?>(UserSettings.Fields.TimeZoneBias) ?? 0,
                UserRoles = userRoles,
                OrganisationUrl = organisation?.GetAttributeValue <string>(Organization.Fields.ExternalBaseURL),
                IsAutoSaveEnabled = organisation?.GetAttributeValue <bool?>(Organization.Fields.AutoSaveEnabled) ?? false,
                OrgLanguageCode = organisation?.GetAttributeValue <int?>(Organization.Fields.Language) ?? 1033,
                OrganisationName = organisation?.GetAttributeValue <string>(Organization.Fields.OrganizationName),
                ThemeName = theme?.GetAttributeValue <string>(Theme.Fields.ThemeName),
                CrmVersion = version
            });
        }
Пример #20
0
        private void Connect_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(Name.Text))
            {
                MessageBox.Show("Enter A Name");
                return;
            }

            if (string.IsNullOrEmpty(ConnString.Text))
            {
                MessageBox.Show("Enter A Connection String");
                return;
            }

            try
            {
                CrmConnection connection = CrmConnection.Parse(ConnString.Text);
                using (OrganizationService orgService = new OrganizationService(connection))
                {
                    WhoAmIRequest  wRequest  = new WhoAmIRequest();
                    WhoAmIResponse wResponse = (WhoAmIResponse)orgService.Execute(wRequest);

                    OrgId = wResponse.OrganizationId.ToString();

                    RetrieveVersionRequest  vRequest  = new RetrieveVersionRequest();
                    RetrieveVersionResponse vResponse = (RetrieveVersionResponse)orgService.Execute(vRequest);

                    Version          = vResponse.Version;
                    ConnectionName   = Name.Text;
                    ConnectionString = ConnString.Text;

                    DialogResult = true;
                    Close();
                }
            }
            catch (Exception)
            {
                //TODO: handle error
                MessageBox.Show("Error Connecting to CRM");
            }
        }
Пример #21
0
        /// <summary>
        /// Connects to a Crm server
        /// </summary>
        /// <param name="parameters">List of parameters</param>
        /// <returns>An exception or an IOrganizationService</returns>
        private object Connect(List <object> parameters)
        {
            WebRequest.DefaultWebProxy = WebRequest.GetSystemWebProxy();

            var detail = (ConnectionDetail)parameters[0];

            SendStepChange("Creating Organization service proxy...");

            // Connecting to Crm server
            try
            {
                var connection = CrmConnection.Parse(detail.GetOrganizationCrmConnectionString());
                var service    = new OrganizationService(connection);

                ((OrganizationServiceProxy)service.InnerService).SdkClientVersion = detail.OrganizationVersion;

                TestConnection(service);

                var vRequest  = new RetrieveVersionRequest();
                var vResponse = (RetrieveVersionResponse)service.Execute(vRequest);

                detail.OrganizationVersion = vResponse.Version;

                var currentConnection = ConnectionsList.Connections.FirstOrDefault(x => x.ConnectionId == detail.ConnectionId);
                if (currentConnection != null)
                {
                    currentConnection.OrganizationVersion = vResponse.Version;
                    currentConnection.SavePassword        = detail.SavePassword;
                    currentConnection.UserPassword        = detail.UserPassword;
                }

                SaveConnectionsFile(ConnectionsList);

                return(service);
            }
            catch (Exception error)
            {
                return(error);
            }
        }
        /// <summary>
        /// The Connect() method first connects to the organization service.
        /// </summary>
        /// <param name="connectionString">Provides service connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Connect(String connectionString, bool promptforDelete)
        {
            try
            {
                // Establish a connection to the organization web service.
                Print("Connecting to the server ...");

                // Connect to the CRM web service using a connection string.
                CrmServiceClient conn = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(connectionString);

                // Cast the proxy client to the IOrganizationService interface.
                _orgService = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;
                Print("connected");

                // Obtain information about the logged on user from the web service.
                Guid       userid     = ((WhoAmIResponse)_orgService.Execute(new WhoAmIRequest())).UserId;
                SystemUser systemUser = (SystemUser)_orgService.Retrieve("systemuser", userid,
                                                                         new ColumnSet(new string[] { "firstname", "lastname" }));
                Println("Logged on user is " + systemUser.FirstName + " " + systemUser.LastName + ".");

                // Retrieve the version of Microsoft Dynamics CRM.
                RetrieveVersionRequest  versionRequest  = new RetrieveVersionRequest();
                RetrieveVersionResponse versionResponse =
                    (RetrieveVersionResponse)_orgService.Execute(versionRequest);
                Println("Microsoft Dynamics CRM version " + versionResponse.Version + ".");

                //enable the action buttons when a connection is available
                this.btnCreate.IsEnabled   = true;
                this.btnRetrieve.IsEnabled = true;
                this.btnUpdate.IsEnabled   = true;
                this.btnDelete.IsEnabled   = true;
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Пример #23
0
        public void AddsFakeVersionRequest()
        {
            var fakedContext = new XrmFakedContext();
            var fakedService = fakedContext.GetFakedOrganizationService();

            var fakeVersionExecutor = new RetrieveVersionRequestExecutor();

            fakedContext.AddFakeMessageExecutor <RetrieveVersionRequest>(fakeVersionExecutor);

            var fakeVersionRequest = new RetrieveVersionRequest();
            var result             = (RetrieveVersionResponse)fakedService.Execute(fakeVersionRequest);
            var version            = result.Version;
            var versionComponents  = version.Split('.');

            var majorVersion = versionComponents[0];
            var minorVersion = versionComponents[1];

#if FAKE_XRM_EASY_9
            Assert.True(int.Parse(majorVersion) >= 9);
#elif FAKE_XRM_EASY_365
            Assert.True(int.Parse(majorVersion) >= 8);

            if (majorVersion == "8")
            {
                Assert.True(int.Parse(minorVersion) >= 2);
            }
#elif FAKE_XRM_EASY_2016
            Assert.True(int.Parse(majorVersion) >= 8);
            Assert.True(int.Parse(minorVersion) >= 0);
            Assert.True(int.Parse(minorVersion) < 2);
#elif FAKE_XRM_EASY_2015
            Assert.True(version.StartsWith("7"));
#elif FAKE_XRM_EASY_2013
            Assert.True(version.StartsWith("6"));
#elif FAKE_XRM_EASY
            Assert.True(version.StartsWith("5"));
#endif
        }
Пример #24
0
        private string GetCurrentVersion()
        {
            TracingService.Trace("{0} - Inside GetCurrentVersion", className);

            string currentVersion = string.Empty;

            RetrieveVersionRequest request = new RetrieveVersionRequest();

            TracingService.Trace("{0} - Retrieving Current Dynamics Version Number", className);

            RetrieveVersionResponse response = (RetrieveVersionResponse)OrganizationService.Execute(request);

            TracingService.Trace("{0} - Retrived Current Dynamics Version Number", className);

            if (response != null && response.Results != null && response.Results.Count > 0)
            {
                currentVersion = response.Version;
            }

            TracingService.Trace("{0} - Current Version Number is {1}", className, currentVersion);
            TracingService.Trace("{0} - Leaving GetCurrentVersion", className);

            return(currentVersion);
        }
Пример #25
0
        private static void GetConnectionDetails(IOrganizationService service)
        {
            if (service != null)
            {
                // Obtain information about the logged on user from the web service.
                Guid userid = ((WhoAmIResponse)service.Execute(new WhoAmIRequest())).UserId;
                //SystemUser systemUser = (SystemUser)service.Retrieve("systemuser", userid,
                //    new ColumnSet(new string[] { "firstname", "lastname" }));
                var systemUser = (Entity)service.Retrieve("systemuser", userid,
                                                          new ColumnSet(new string[] { "firstname", "lastname" }));
                Console.WriteLine("Connected...");
                Console.WriteLine("Logged on user is {0} {1}.", systemUser.Attributes["firstname"], systemUser.Attributes["lastname"]);

                // Retrieve the version of Microsoft Dynamics CRM.
                RetrieveVersionRequest  versionRequest  = new RetrieveVersionRequest();
                RetrieveVersionResponse versionResponse =
                    (RetrieveVersionResponse)service.Execute(versionRequest);
                Console.WriteLine("Microsoft Dynamics CRM version {0}.", versionResponse.Version);
            }
            else
            {
                Console.WriteLine("Connection failed!");
            }
        }
Пример #26
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


                    // Obtain information about the logged on user from the web service.
                    Guid       userid     = ((WhoAmIResponse)service.Execute(new WhoAmIRequest())).UserId;
                    SystemUser systemUser = (SystemUser)service.Retrieve("systemuser", userid,
                                                                         new ColumnSet(new string[] { "firstname", "lastname" }));
                    Console.WriteLine("Logged on user is {0} {1}.", systemUser.FirstName, systemUser.LastName);

                    // Retrieve the version of Microsoft Dynamics CRM.
                    RetrieveVersionRequest  versionRequest  = new RetrieveVersionRequest();
                    RetrieveVersionResponse versionResponse =
                        (RetrieveVersionResponse)service.Execute(versionRequest);
                    Console.WriteLine("Microsoft Dynamics CRM version {0}.", versionResponse.Version);

                    // Instantiate an account object. Note the use of option set enumerations defined in OptionSets.cs.
                    // Refer to the Entity Metadata topic in the SDK documentation to determine which attributes must
                    // be set for each entity.
                    Account account = new Account {
                        Name = "Fourth Coffee"
                    };
                    account.AccountCategoryCode = new OptionSetValue((int)AccountAccountCategoryCode.PreferredCustomer);
                    account.CustomerTypeCode    = new OptionSetValue((int)AccountCustomerTypeCode.Investor);

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

                    Console.Write("{0} {1} created, ", account.LogicalName, account.Name);

                    // Retrieve the several attributes from the new account.
                    ColumnSet cols = new ColumnSet(
                        new String[] { "name", "address1_postalcode", "lastusedincampaign" });

                    Account retrievedAccount = (Account)service.Retrieve("account", _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.WriteLine("and updated.");

                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                #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();
            }
        }
Пример #27
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
                    // Obtain information about the logged on user from the web service.
                    Guid       userid     = ((WhoAmIResponse)service.Execute(new WhoAmIRequest())).UserId;
                    SystemUser systemUser = (SystemUser)service.Retrieve("systemuser", userid,
                                                                         new ColumnSet(new string[] { "firstname", "lastname" }));
                    Console.WriteLine("Logged on user is {0} {1}.", systemUser.FirstName, systemUser.LastName);

                    // Retrieve the version of Microsoft Dynamics CRM.
                    RetrieveVersionRequest  versionRequest  = new RetrieveVersionRequest();
                    RetrieveVersionResponse versionResponse =
                        (RetrieveVersionResponse)service.Execute(versionRequest);
                    Console.WriteLine("Microsoft Dynamics CRM version {0}.", versionResponse.Version);

                    bool fetchEverything = false;

                    if (fetchEverything)
                    {
                        QueryExpression queGetAllIncidents = new QueryExpression("incident");
                        queGetAllIncidents.ColumnSet = new ColumnSet(true);
                        EntityCollection allIncidents = service.RetrieveMultiple(queGetAllIncidents);
                        WriteToJson(allIncidents.Entities[0], @"entity0.json");

                        QueryExpression queGetAllContacts = new QueryExpression("contact");
                        queGetAllContacts.ColumnSet = new ColumnSet(true);
                        EntityCollection allContacts = service.RetrieveMultiple(queGetAllContacts);
                        WriteToJson(allContacts, @"contacts.json");

                        QueryExpression queGetAllAccounts = new QueryExpression("account");
                        queGetAllAccounts.ColumnSet = new ColumnSet(true);
                        //queGetAllAccounts.ColumnSet = new ColumnSet(new String[]{ "AccountId", "Name" });
                        EntityCollection allAccounts = service.RetrieveMultiple(queGetAllAccounts);
                        WriteToJson(allAccounts, @"accounts.json");
                    }


                    //TODO - fetch by name
                    var incident = new Incident
                    {
                        Title = "Testing From Roy",
                        //PrimaryContactId = new EntityReference("contact", new Guid("{6a9334ad-bd04-ea11-a811-000d3a4a1025}")),
                        CustomerId = new EntityReference("account", new Guid("{852179cc-e2a6-e911-a97f-000d3a2cba5f}"))
                    };

                    var       incidentId = service.Create(incident);
                    ColumnSet cols       = new ColumnSet(
                        new String[] { "title", "new_tguvot_text" });

                    Incident retrievedIncident = (Incident)service.Retrieve("incident", incidentId, cols);
                    Console.Write("retrieved, ");

                    var incidentAttributes = retrievedIncident.Attributes;
                    incidentAttributes["new_tguvot_text"] = 5;

                    service.Update(retrievedIncident);
                    Console.WriteLine("and updated.");
                }
                #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();
            }
        }
Пример #28
0
        private void Start_Api(string var, bool start)
        {
            // The connection to the Organization web service.
            OrganizationServiceProxy  serviceProxy = null;
            EntityReferenceCollection records      = null;

            // Obtain the target organization's web address and client logon credentials
            // from the user by using a helper class.
            ServerConnection serverConnect = new ServerConnection();

            ServerConnection.Configuration config = serverConnect.GetServerConfiguration();

            // Establish an authenticated connection to the Organization web service.
            serviceProxy = new OrganizationServiceProxy(config.OrganizationUri, config.HomeRealmUri,
                                                        config.Credentials, config.DeviceCredentials);

            CRUDOperations app = new CRUDOperations();

            // Create any records that must exist in the database. These record references are
            // stored in a collection so the records can be deleted later.
            records =
                app.CreateRequiredEntityRecords(serviceProxy);


            // Enable early-bound entity types. This enables use of IntelliSense in Visual Studio
            // and avoids spelling errors in attribute names when using the Entity property bag.
            serviceProxy.EnableProxyTypes();

            // Here we will use the interface instead of the proxy object.
            IOrganizationService service = (IOrganizationService)serviceProxy;

            // Display information about the logged on user.
            Guid       userid     = ((WhoAmIResponse)service.Execute(new WhoAmIRequest())).UserId;
            SystemUser systemUser = (SystemUser)service.Retrieve("systemuser", userid,
                                                                 new ColumnSet(new string[] { "firstname", "lastname" }));

            Console.WriteLine("Logged on user is {0} {1}.", systemUser.FirstName, systemUser.LastName);

            // Retrieve the version of Microsoft Dynamics CRM.
            RetrieveVersionRequest  versionRequest  = new RetrieveVersionRequest();
            RetrieveVersionResponse versionResponse =
                (RetrieveVersionResponse)service.Execute(versionRequest);

            Console.WriteLine("Microsoft Dynamics CRM version {0}.", versionResponse.Version);
            // Perform the primary operation of this sample.



            // Some exceptions to consider catching.
            //<snippetCRUDOperations3>

            //</snippetCRUDOperations3>


            if (start)
            {
                MyTimer.Interval = (Convert.ToInt32(var) * 60 * 1000); // 1 mins
                MyTimer.Tick    += (sender2, e2) => MyTimer_Tick(sender2, e2, serviceProxy, records);
                MyTimer.Start();
            }
            else
            {
                MyTimer.Stop();
            }
        }
Пример #29
0
        /// <summary>
        /// The Run() method first connects to the Organization service. Afterwards,
        /// basic create, retrieve, update, and delete entity operations are performed.
        /// </summary>
        /// <param name="connectionString">Provides service connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(String connectionString, bool promptforDelete)
        {
            try
            {
                // Connect to the CRM web service using a connection string.
                CrmServiceClient conn = new Xrm.Tooling.Connector.CrmServiceClient(connectionString);

                // Cast the proxy client to the IOrganizationService interface.
                _orgService = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;

                //Create any entity records this sample requires.
                CreateRequiredRecords();

                // Obtain information about the logged on user from the web service.
                Guid       userid     = ((WhoAmIResponse)_orgService.Execute(new WhoAmIRequest())).UserId;
                SystemUser systemUser = (SystemUser)_orgService.Retrieve("systemuser", userid,
                                                                         new ColumnSet(new string[] { "firstname", "lastname" }));
                Console.WriteLine("Logged on user is {0} {1}.", systemUser.FirstName, systemUser.LastName);

                // Retrieve the version of Microsoft Dynamics CRM.
                RetrieveVersionRequest  versionRequest  = new RetrieveVersionRequest();
                RetrieveVersionResponse versionResponse =
                    (RetrieveVersionResponse)_orgService.Execute(versionRequest);
                Console.WriteLine("Microsoft Dynamics CRM version {0}.", versionResponse.Version);

                // Instantiate an account object. Note the use of option set enumerations defined in OptionSets.cs.
                // Refer to the Entity Metadata topic in the SDK documentation to determine which attributes must
                // be set for each entity.
                Account account = new Account {
                    Name = "Fourth Coffee"
                };
                account.AccountCategoryCode = new OptionSetValue((int)AccountAccountCategoryCode.PreferredCustomer);
                account.CustomerTypeCode    = new OptionSetValue((int)AccountCustomerTypeCode.Investor);

                // Create an account record named Fourth Coffee.
                _accountId = _orgService.Create(account);

                Console.Write("{0} {1} created, ", account.LogicalName, account.Name);

                // Retrieve the several attributes from the new account.
                ColumnSet cols = new ColumnSet(
                    new String[] { "name", "address1_postalcode", "lastusedincampaign" });

                Account retrievedAccount = (Account)_orgService.Retrieve("account", _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.
                _orgService.Update(retrievedAccount);
                Console.WriteLine("and updated.");

                // Delete any entity records this sample created.
                DeleteRequiredRecords(promptforDelete);
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
        private void Connect_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(Name.Text))
            {
                MessageBox.Show("Enter A Name");
                return;
            }

            if (string.IsNullOrEmpty(ConnString.Text))
            {
                MessageBox.Show("Enter A Connection String");
                return;
            }

            try
            {
                CrmConnection connection = CrmConnection.Parse(ConnString.Text);
                using (OrganizationService orgService = new OrganizationService(connection))
                {
                    WhoAmIRequest wRequest = new WhoAmIRequest();
                    WhoAmIResponse wResponse = (WhoAmIResponse)orgService.Execute(wRequest);

                    OrgId = wResponse.OrganizationId.ToString();

                    RetrieveVersionRequest vRequest = new RetrieveVersionRequest();
                    RetrieveVersionResponse vResponse = (RetrieveVersionResponse)orgService.Execute(vRequest);

                    Version = vResponse.Version;
                    ConnectionName = Name.Text;
                    ConnectionString = ConnString.Text;

                    DialogResult = true;
                    Close();
                }
            }
            catch (Exception)
            {
                //TODO: handle error
                MessageBox.Show("Error Connecting to CRM");
            }
        }
Пример #31
0
        public RetrieveVersionResponse GetVersion()
        {
            RetrieveVersionRequest versionRequest = new RetrieveVersionRequest();

            return((RetrieveVersionResponse)OrganizationService.Execute(versionRequest));
        }
Пример #32
0
    public IOrganizationService ConnectService()
    {
        IOrganizationService organizationService = null;

        var connection = ConfigurationManager.ConnectionStrings["CrmConnection"].ConnectionString;
        CrmServiceClient serviceClient = new CrmServiceClient(connection);

        /*
         * Logger.Info("Connected Org Friendly Name : " + serviceClient.ConnectedOrgFriendlyName);
         * Logger.Info("CrmConnectOrgUriActual :" + serviceClient.CrmConnectOrgUriActual);
         * Logger.Info("Service Is Ready :  " + serviceClient.IsReady);
         * Logger.Info("Trying to initialise OrganizationServiceProxy");
         */
        try
        {
            if (serviceClient.IsReady)
            {
                //Logger.Info("Connection is ready : initiating Service Client");
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                organizationService = (IOrganizationService)serviceClient.OrganizationWebProxyClient != null
                                    ? (IOrganizationService)serviceClient.OrganizationWebProxyClient
                                    : (IOrganizationService)serviceClient.OrganizationServiceProxy;

                if (organizationService != null)
                {
                    //Logger.Info("Seeking CRM Version");
                    RetrieveVersionRequest  versionRequest  = new RetrieveVersionRequest();
                    RetrieveVersionResponse versionResponse = (RetrieveVersionResponse)organizationService.Execute(versionRequest);
                    System.Console.WriteLine("Microsoft Dynamics CRM Version {0}", versionResponse.Version);
                    //Logger.Info("Found CRM Version " + versionResponse.Version);

                    // Test Call
                    Guid WhoAmIid = ((WhoAmIResponse)organizationService.Execute(new WhoAmIRequest())).UserId;
                    if (WhoAmIid != Guid.Empty)
                    {
                        Logger.Info("Successful connection to CRM");
                        //Logger.Info("WhoAmI : " + WhoAmIid);
                        Entity user = organizationService.Retrieve("systemuser", WhoAmIid, new ColumnSet(true));
                        if (user != null)
                        {
                            Logger.Info("UserName : "******"fullname"));
                            //Logger.Info("DomainName : " + user.GetAttributeValue<String>("domainname"));
                        }
                        else
                        {
                            Logger.Info("Unable to get user from CRM : WhoAmI request failed");
                        }
                    }
                }
            }
            else
            {
                Logger.Info("Last CRM Error : " + serviceClient.LastCrmError);
                Logger.Info("Last CRM Exception : " + serviceClient.LastCrmException);
                Logger.Info("Service was not ready for initialisation : IOrganizationService provision failed. Exiting");
            }
        }
        catch (FaultException <IOrganizationService> ex)
        {
            Logger.Fatal(ex.Message);
            throw;
        }
        catch (CommunicationException ex)
        {
            Logger.Fatal(ex.Message);
            throw;
        }
        catch (Exception ex)
        {
            Logger.Fatal(ex.Message);
            throw;
        }

        return(organizationService);
    }
        private RetrieveVersionResponse ConnectToCrm(string connectionString)
        {
            try
            {
                CrmConnection connection = CrmConnection.Parse(connectionString);
                using (OrganizationService orgService = new OrganizationService(connection))
                {
                    WhoAmIRequest wRequest = new WhoAmIRequest();
                    WhoAmIResponse wResponse = (WhoAmIResponse)orgService.Execute(wRequest);
                    _logger.WriteToOutputWindow("Connected To CRM Organization: " + wResponse.OrganizationId, Logger.MessageType.Info);

                    OrgId = wResponse.OrganizationId.ToString();

                    RetrieveVersionRequest vRequest = new RetrieveVersionRequest();
                    RetrieveVersionResponse vResponse = (RetrieveVersionResponse)orgService.Execute(vRequest);
                    _logger.WriteToOutputWindow("Version: " + vResponse.Version, Logger.MessageType.Info);

                    return vResponse;
                }
            }
            catch (FaultException<OrganizationServiceFault> crmEx)
            {
                _logger.WriteToOutputWindow("Error Connecting To CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error);
                return null;
            }
            catch (Exception ex)
            {
                _logger.WriteToOutputWindow("Error Connecting To CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error);
                return null;
            }
        }
Пример #34
0
        public void Experiment_For_Crm_Version_Request()
        {
            var connectionString = ConfigurationManager.ConnectionStrings["CrmOrganisation"];
            var serviceProvider = new CrmServiceProvider(new ExplicitConnectionStringProviderWithFallbackToConfig() { OrganisationServiceConnectionString = connectionString.ConnectionString },
                                                         new CrmClientCredentialsProvider());

            var orgService = serviceProvider.GetOrganisationService();
            using (orgService as IDisposable)
            {
                var req = new RetrieveVersionRequest();
                var resp = (RetrieveVersionResponse)orgService.Execute(req);
                //assigns the version to a string
                string versionNumber = resp.Version;
                Console.WriteLine(versionNumber);
            }
        }
Пример #35
0
        /// <summary>
        /// The Run() method first connects to the organization service. Afterwards,
        /// basic create, retrieve, update, and delete entity operations are performed.
        /// </summary>
        /// <param name="connectionString">Provides service connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(String connectionString, bool promptforDelete)
        {
            try
            {
                // Establish a connection to the organization web service.
                Print("Connecting to the server ...");
                Microsoft.Xrm.Client.CrmConnection connection = CrmConnection.Parse(connectionString);

                // Obtain an organization service proxy.
                // The using statement assures that the service proxy will be properly disposed.
                using (_orgService = new OrganizationService(connection))
                {
                    Print("connected");
                    Print("Authenticating the user ...");

                    // Create any entity records this sample requires.
                    CreateRequiredRecords();

                    // Obtain information about the logged on user from the web service.
                    Guid userid = ((WhoAmIResponse)_orgService.Execute(new WhoAmIRequest())).UserId;
                    SystemUser systemUser = (SystemUser)_orgService.Retrieve("systemuser", userid,
                        new ColumnSet(new string[] { "firstname", "lastname" }));
                    Println("Logged on user is " + systemUser.FirstName + " " + systemUser.LastName + ".");

                    // Retrieve the version of Microsoft Dynamics CRM.
                    RetrieveVersionRequest versionRequest = new RetrieveVersionRequest();
                    RetrieveVersionResponse versionResponse =
                        (RetrieveVersionResponse)_orgService.Execute(versionRequest);
                    Println("Microsoft Dynamics CRM version " + versionResponse.Version + ".");

                    // Instantiate an account object. Note the use of option set enumerations defined in OptionSets.cs.
                    // Refer to the Entity Metadata topic in the SDK documentation to determine which attributes must
                    // be set for each entity.
                    Account account = new Account { Name = "Fourth Coffee" };
                    account.AccountCategoryCode = new OptionSetValue((int)AccountAccountCategoryCode.PreferredCustomer);
                    account.CustomerTypeCode = new OptionSetValue((int)AccountCustomerTypeCode.Investor);

                    // Create an account record named Fourth Coffee.
                    _accountId = _orgService.Create(account);

                    Println(account.LogicalName + " " + account.Name + " created, ");

                    // Retrieve several attributes from the new account.
                    ColumnSet cols = new ColumnSet(
                        new String[] { "name", "address1_postalcode", "lastusedincampaign" });

                    Account retrievedAccount = (Account)_orgService.Retrieve("account", _accountId, cols);
                    Print("retrieved, ");

                    // Update the postal code attribute.
                    retrievedAccount.Address1_PostalCode = "98052";

                    // The address 2 postal code was set accidentally, so set it to null.
                    retrievedAccount.Address2_PostalCode = null;

                    // Shows use of a Money value.
                    retrievedAccount.Revenue = new Money(5000000);

                    // Shows use of a Boolean value.
                    retrievedAccount.CreditOnHold = false;

                    // Update the account record.
                    _orgService.Update(retrievedAccount);
                    Print("and updated.");

                    // Delete any entity records this sample created.
                    DeleteRequiredRecords(promptforDelete);
                }
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Пример #36
0
        /// <summary>
        /// This method first connects to the Organization service. Afterwards,
        /// basic create, retrieve, update, and delete entity operations are performed.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetCRUDOperations1>
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig) )
                {
                    _serviceProxy.EnableProxyTypes();
                    _service = (IOrganizationService)_serviceProxy;

                    CreateRequiredRecords();
                    ServiceContext svcContext = new ServiceContext(_service);

                    var accounts = from a in svcContext.AccountSet
                                   select new Account
                                   {
                                       Name = a.Name,
                                       Address1_County = a.Address1_County
                                   };
                    System.Console.WriteLine("List all accounts in CRM");
                    System.Console.WriteLine("========================");
                    foreach (var a in accounts)
                    {
                        System.Console.WriteLine(a.Name + " " + a.Address1_County);
                    }
                    //</snippetCreateALinqQuery1>
                    System.Console.WriteLine();
                    System.Console.WriteLine("<End of Listing>");
                    System.Console.WriteLine();

                    var queryContacts = from c in svcContext.ContactSet
                                        select new Contact
                                        {
                                            FirstName = c.FirstName,
                                            LastName = c.LastName,
                                            Address1_City = c.Address1_City
                                        };
                    System.Console.WriteLine("List all contacts in CRM");
                    System.Console.WriteLine("=====================================");
                    foreach (var c in queryContacts)
                    {
                        System.Console.WriteLine(c.FirstName + " " +
                            c.LastName + " " + c.Address1_City);
                    }

                    System.Console.WriteLine();
                    System.Console.WriteLine("<End of Listing>");
                    System.Console.WriteLine();

                    // Display information about the logged on user.
                    Guid userid = ((WhoAmIResponse)_serviceProxy.Execute(new WhoAmIRequest())).UserId;
                    SystemUser systemUser = (SystemUser)_serviceProxy.Retrieve("systemuser", userid,
                        new ColumnSet(new string[] {"firstname", "lastname"}));
                    Console.WriteLine("Logged on user is {0} {1}.", systemUser.FirstName, systemUser.LastName);

                    // Retrieve the version of Microsoft Dynamics CRM.
                    RetrieveVersionRequest versionRequest = new RetrieveVersionRequest();
                    RetrieveVersionResponse versionResponse =
                        (RetrieveVersionResponse)_serviceProxy.Execute(versionRequest);
                    Console.WriteLine("Microsoft Dynamics CRM version {0}.", versionResponse.Version);

                    //<snippetCRUDOperations2>

                    // Instantiate an account object. Note the use of the option set enumerations defined in OptionSets.cs.
                    // 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" };
                    account.AccountCategoryCode = new OptionSetValue((int)AccountAccountCategoryCode.PreferredCustomer);
                    account.CustomerTypeCode = new OptionSetValue((int)AccountCustomerTypeCode.Investor);

                    // Create an account record named Fourth Coffee.
                    _accountId = _serviceProxy.Create(account);

                    //</snippetCRUDOperations2>
                    Console.Write("{0} {1} created, ", account.LogicalName, account.Name);

                    // Retrieve the account containing several of its attributes.
                    ColumnSet cols = new ColumnSet(
                        new String[] { "name", "address1_postalcode", "lastusedincampaign" });

                    Account retrievedAccount = (Account)_serviceProxy.Retrieve("account", _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.
                    _serviceProxy.Update(retrievedAccount);
                    Console.WriteLine("and updated.");

                    DeleteRequiredRecords(promptforDelete);
                }
                //</snippetCRUDOperations1>
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Пример #37
0
        /// <summary>
        /// Connects to a Crm server
        /// </summary>
        /// <param name="parameters">List of parameters</param>
        /// <returns>An exception or an IOrganizationService</returns>
        private object Connect(List<object> parameters)
        {
            WebRequest.DefaultWebProxy = WebRequest.GetSystemWebProxy();

            var detail = (ConnectionDetail)parameters[0];
            SendStepChange("Creating Organization service proxy...");

            // Connecting to Crm server
            try
            {
                var service = (OrganizationService)detail.GetOrganizationService();

                ((OrganizationServiceProxy)service.InnerService).SdkClientVersion = detail.OrganizationVersion;

                TestConnection(service);

                // If the current connection detail does not contain the web
                // application url, we search for it
                if (string.IsNullOrEmpty(detail.WebApplicationUrl) || string.IsNullOrEmpty(detail.OrganizationDataServiceUrl))
                {
                    var discoService = (DiscoveryService)detail.GetDiscoveryService();
                    var result = (RetrieveOrganizationResponse)discoService.Execute(new RetrieveOrganizationRequest { UniqueName = detail.Organization });
                    detail.WebApplicationUrl = result.Detail.Endpoints[EndpointType.WebApplication];
                    detail.OrganizationDataServiceUrl = result.Detail.Endpoints[EndpointType.OrganizationDataService];
                }

                // We search for organization version
                var vRequest = new RetrieveVersionRequest();
                var vResponse = (RetrieveVersionResponse)service.Execute(vRequest);

                detail.OrganizationVersion = vResponse.Version;

                var currentConnection = ConnectionsList.Connections.FirstOrDefault(x => x.ConnectionId == detail.ConnectionId);
                if (currentConnection != null)
                {
                    currentConnection.WebApplicationUrl = detail.WebApplicationUrl;
                    currentConnection.OrganizationDataServiceUrl = detail.OrganizationDataServiceUrl;
                    currentConnection.OrganizationVersion = vResponse.Version;
                    currentConnection.SavePassword = detail.SavePassword;
                    detail.CopyPasswordTo(currentConnection);
                }

                detail.LastUsedOn = DateTime.Now;

                SaveConnectionsFile();

                return service;
            }
            catch (Exception error)
            {
                return error;
            }
        }
Пример #38
0
        //<snippetCRUDOperations1>
        /// <summary>
        /// This method performs entity create, retrieve, and update operations.
        /// The delete operation is handled in the DeleteRequiredrecords() method.
        /// </summary>
        /// <param name="serviceProxy">An established connection to the Organization web service.</param>
        /// <param name="records">A collection of entity records created by this sample.</param>
        public void Run(OrganizationServiceProxy serviceProxy, EntityReferenceCollection records)
        {
            // Enable early-bound entity types. This enables use of IntelliSense in Visual Studio
            // and avoids spelling errors in attribute names when using the Entity property bag.
            serviceProxy.EnableProxyTypes();

            // Here we will use the interface instead of the proxy object.
            IOrganizationService service = (IOrganizationService)serviceProxy;

            // Display information about the logged on user.
            Guid userid = ((WhoAmIResponse)service.Execute(new WhoAmIRequest())).UserId;
            SystemUser systemUser = (SystemUser)service.Retrieve("systemuser", userid,
                new ColumnSet(new string[] { "firstname", "lastname" }));
            Console.WriteLine("Logged on user is {0} {1}.", systemUser.FirstName, systemUser.LastName);

            // Retrieve the version of Microsoft Dynamics CRM.
            RetrieveVersionRequest versionRequest = new RetrieveVersionRequest();
            RetrieveVersionResponse versionResponse =
                (RetrieveVersionResponse)service.Execute(versionRequest);
            Console.WriteLine("Microsoft Dynamics CRM version {0}.", versionResponse.Version);

            //<snippetCRUDOperations2>
            // Instantiate an account object. Note the use of the option set enumerations defined
            // in OptionSets.cs.
            Account account = new Account { Name = "Fourth Coffee" };
            account.AccountCategoryCode = new OptionSetValue((int)AccountAccountCategoryCode.PreferredCustomer);
            account.CustomerTypeCode = new OptionSetValue((int)AccountCustomerTypeCode.Investor);

            // Create an account record named Fourth Coffee.
            // Save the record reference so we can delete it during cleanup later.
            Guid accountId = service.Create(account);
            //</snippetCRUDOperations2>
            var eref = new EntityReference(Account.EntityLogicalName, accountId);
            eref.Name = account.Name;
            records.Add(eref);

            Console.Write("{0} {1} created, ", account.LogicalName, account.Name);

            // Retrieve the account containing several of its attributes. This results in
            // better performance compared to retrieving all attributes.
            ColumnSet cols = new ColumnSet(
                new String[] { "name", "address1_postalcode", "lastusedincampaign" });

            Account retrievedAccount = (Account)service.Retrieve("account", accountId, cols);
            Console.Write("retrieved, ");

            // Update the postal code attribute.
            retrievedAccount.Address1_PostalCode = "98052";

            // There is no address 2 postal code needed.
            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.WriteLine("and updated.");
        }
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Create a date/time attribute for account entity with UserLocal behavior.
        /// Create an account record.
        /// Retrieve the value in the new date/time attribute.
        /// Update attribute to set the behavior to DateOnly.
        /// Create another account record.
        /// Retrieve both the account records to compare the date value retrieved.
        /// Use the "ConvertDateandTimeRequest" message to change the behavior for the
        /// existing records.
        /// Optionally delete/revert any attributes 
        /// that were created/changed for this sample.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptForDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {

                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, 
                    serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // Check if you are running the correct version of CRM.
                    // This sample requires that the CRM version be 7.1.0.xxxx or later.
                    RetrieveVersionRequest crmVersionReq = new RetrieveVersionRequest();
                    RetrieveVersionResponse crmVersionResp = (RetrieveVersionResponse)_serviceProxy.Execute(crmVersionReq);

                    if (String.CompareOrdinal("7.1.0.0", crmVersionResp.Version) < 0)
                    {
                        // Create required records for the sample.
                        CreateRequiredRecords();

                        // Use the ConvertDateandTimeBehaviorRequest SDK message to change
                        // the behavior of the date and time values in the custom attribute
                        // (new_SampleDateTimeAttribute) for the account entity.
                        ConvertDateAndTimeBehaviorRequest request = new ConvertDateAndTimeBehaviorRequest()
                        {
                            Attributes = new EntityAttributeCollection() 
                                    { 
                                        new KeyValuePair<string, StringCollection>("account", new StringCollection() 
                                        { "new_sampledatetimeattribute" }) 
                                    },
                            ConversionRule = DateTimeBehaviorConversionRule.SpecificTimeZone.Value,
                            TimeZoneCode = 190, // Time zone code for India Standard Time (IST) in CRM
                            AutoConvert = false // Conversion must be done using ConversionRule
                        };

                        // Execute the request
                        ConvertDateAndTimeBehaviorResponse response = (ConvertDateAndTimeBehaviorResponse)_serviceProxy.Execute(request);
                        
                        Console.WriteLine("***************************************");
                        Console.WriteLine("Executed the ConvertDateAndTimeBehaviorRequest SDK message.\n");

                        // Wait for two seconds to let the async job be created
                        System.Threading.Thread.Sleep(2000);

                        if (response.JobId != null)
                        {
                            Console.WriteLine("An async job created with ID: {0}", response.JobId.ToString());
                        }

                        // Retrieve the job completion details based on the Job ID                    
                        ColumnSet cs = new ColumnSet("statecode", "statuscode", "friendlymessage", "message");
                        Console.WriteLine("Waiting for the async job to complete...\n");
                        
                        AsyncOperation crmAsyncJob = new AsyncOperation();
                        while (response.JobId != null &amp;&amp; waitCount > 0)
                        {
                            // Check to see if the async operation is complete
                            crmAsyncJob =
                              (AsyncOperation)_serviceProxy.Retrieve(AsyncOperation.EntityLogicalName,
                                           response.JobId, cs);
                            if (crmAsyncJob.StateCode.HasValue &amp;&amp;
                                    crmAsyncJob.StateCode.Value == AsyncOperationState.Completed &amp;&amp; 
                                    crmAsyncJob.StatusCode.Value == (int)asyncoperation_statuscode.Succeeded)
                            {
                                waitCount = 0;                                
                                
                                Console.WriteLine("The async job is complete.\n");
                                Console.WriteLine("****************************");
                                Console.WriteLine(crmAsyncJob.FriendlyMessage);
                                Console.WriteLine("****************************");
                                Console.WriteLine(crmAsyncJob.Message);
                                Console.WriteLine("****************************\n");

                                // Retrieve both the account records created earlier to check the date value
                                Console.WriteLine("Retrieving the date and time values after the conversion...\n");
                                // Create a column set to define which attributes should be retrieved.
                                ColumnSet attributes = new ColumnSet(new string[] { "name", "new_sampledatetimeattribute" });

                                Account retrievedAccount1 = (Account)_serviceProxy.Retrieve(Account.EntityLogicalName, _account1ID, attributes);
                                Account retrievedAccount2 = (Account)_serviceProxy.Retrieve(Account.EntityLogicalName, _account2ID, attributes);

                                Console.WriteLine("'{0}' is: {1}", retrievedAccount1.GetAttributeValue<String>("name"), retrievedAccount1.GetAttributeValue<DateTime>("new_sampledatetimeattribute"));
                                Console.WriteLine("'{0}' is: {1}\n", retrievedAccount2.GetAttributeValue<String>("name"), retrievedAccount2.GetAttributeValue<DateTime>("new_sampledatetimeattribute"));
                                Console.WriteLine("The behavior converted to DateOnly for account record ('Sample Account 1')\nbased on the specified conversion rule.\n");
                                Console.WriteLine("No changes to 'Sample Account 2' because it was already DateOnly.\n");
                                Console.WriteLine("***************************************\n");
                            }
                            else
                            {
                                waitCount--;
                                System.Threading.Thread.Sleep(1000);
                            }
                        }

                        // If the async job is taking tool long to process,
                        // inform the user about the same.
                        if (waitCount == 0 &amp;&amp; crmAsyncJob.StateCode.Value != (AsyncOperationState.Completed))
                        {
                            Console.WriteLine("The async job is taking too long to complete. Aborting the sample.");
                        }

                        // Prompt the user to delete the records and attribute created by the sample.
                        DeleteRequiredRecords(promptForDelete);
                    }
                    else
                    {
                        Console.WriteLine("This sample cannot be run against the current version of CRM.");
                        Console.WriteLine("Upgrade your CRM instance to the latest version to run this sample.");
                    }
                }