public static IOrganizationService ObtenerConexion()
        {
            try
            {
                connection = string.Format(ConfigurationManager.AppSettings["Connection_CRM"], urlCRM, usuarioCRM, claveCRM);
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                conn = new CrmServiceClient(connection);

                //Validamos si se pudo realizar la Conexión
                if (conn.IsReady)
                {
                    _orgService = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)
                                  conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;
                    conn.Dispose();
                    conn = null;
                    return(_orgService);
                }
                else
                {
                    conn.Dispose();
                    conn = null;
                    return(_orgService);
                }
            }
            catch (Exception ex)
            {
                string ruta = ConfigurationManager.AppSettings["PathLogServicio"];

                ZthMetodosVarios.Metodos.GuardarLog(ruta, "Se ha producido el siguiente error: " + ex.Message.ToString());
                throw new Exception(ex.Message.ToString());
            }
        }
Esempio n. 2
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

                    // Create a queue instance and set its property values.
                    var newQueue = new Queue()
                    {
                        Name        = "Example Queue.",
                        Description = "This is an example queue."
                    };

                    // Create a new queue instance.
                    _queueId = service.Create(newQueue);

                    Console.WriteLine("Created {0}.", newQueue.Name);
                    #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();
            }
        }
        /// <summary>
        /// Tests the CRM Connection
        /// </summary>
        /// <param name="connectionString">CRM Connection String</param>
        /// <returns>Returns <see cref="bool"/> if the connection succeeded.</returns>
        public bool TestCRMConnection(string connectionString)
        {
            CrmServiceClient crmServiceClient = null;

            try
            {
                crmServiceClient = new CrmServiceClient(connectionString);

                if (crmServiceClient.IsReady)
                {
                    return(true);
                }
                else
                {
                    CrmConnectionException connectionException = new CrmConnectionException(crmServiceClient.LastCrmError, crmServiceClient.LastCrmException.InnerException);
                    throw connectionException;
                }
            }
            catch (Exception ex)
            {
                ToolingConnector.Log.Error(ex.Message, ex);
                throw;
            }
            finally
            {
                if (crmServiceClient != null)
                {
                    crmServiceClient.Dispose();
                }
            }
        }
        [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 account record created
                    Entity accountRecord = service.Retrieve("account", _accountId, new ColumnSet(true));

                    //Updated the ownerid attribute to the user who want to own the record
                    accountRecord["ownerid"] = new EntityReference(SystemUser.EntityLogicalName, _otherUserId);

                    // Execute the Request
                    service.Update(accountRecord);

                    Console.WriteLine("The account is owned by new owner.");

                    #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. 5
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 accountRecord = service.Retrieve("account", _accountId, new Microsoft.Xrm.Sdk.Query.ColumnSet(true));
                    accountRecord["ownerid"] = new EntityReference(Team.EntityLogicalName, _teamId);
                    service.Update(accountRecord);
                    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();
            }
        }
        protected override void EndProcessing()
        {
            base.EndProcessing();

            if (ServiceClient != null)
            {
                ServiceClient.Dispose();
            }
        }
Esempio n. 7
0
        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

                    CreateMarketingList(service);
                    DistributeCampaign(service);

                    #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();
            }
        }
Esempio n. 8
0
 public virtual void Dispose(bool disposing)
 {
     if (!this.disposed)
     {
         if (disposing)
         {
             conn.Dispose();
         }
         this.disposed = true;
     }
 }
Esempio n. 9
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
                    // TODO Add demonstration code here
                    CloneProductRequest cloneReq = new CloneProductRequest
                    {
                        Source = new EntityReference(Product.EntityLogicalName, _productId)
                    };

                    CloneProductResponse cloned = (CloneProductResponse)ServiceProxy.Execute(cloneReq);
                    _productCloneId = cloned.ClonedProduct.Id;
                    #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;
                    }
                }
            }
            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)
                {
                    _serviceContext = new ServiceContext(service);
                    // Create any entity records that the demonstration code requires
                    SetUpSample(service);
                    #region Demonstrate
                    ConfigureActivityFeeds(service);
                    PostToRecordWalls(service);
                    PostToPersonalWalls(service);
                    ShowRecordWalls(service);
                    #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. 11
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

                    CreateCustomer(service);
                    CreateSalesOrder(service);
                    CloseSalesOrder(service);
                    DeleteRequiredRecords(service, prompt);
                    #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;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

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

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Esempio n. 12
0
        public static void ETLLegislationData(Regulation legData, CrmServiceClient existingService = null, int top = 0)
        {
            CrmServiceClient service = null;

            try
            {
                service = existingService == null?CrmSdkHelper.Connect() : existingService;

                if (service != null)
                {
                    Console.BackgroundColor = ConsoleColor.DarkGreen;

                    Console.WriteLine("Connected to the organization server for " + service?.CrmConnectOrgUriActual?.AbsoluteUri ?? service?.ConnectedOrgFriendlyName);

                    if (service.IsReady)
                    {
                        Console.WriteLine(Environment.NewLine + "-----UPDATING LEGISLATION DATA-----" + Environment.NewLine + ":)");
                        CrmSdkHelper.CreateOrUpdateLegislations(service, legData, top);
                    }
                    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)

            {
                CrmSdkHelper.HandleException(ex);
            }


            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }
            }
        }
Esempio n. 13
0
        public static void DeleteQuestionnaireData(CrmServiceClient existingService = null)
        {
            CrmServiceClient service = null;

            try
            {
                service = existingService == null?CrmSdkHelper.Connect() : existingService;

                if (service != null)
                {
                    Console.BackgroundColor = ConsoleColor.DarkGreen;

                    Console.WriteLine("Connected to the organization server for " + service?.CrmConnectOrgUriActual?.AbsoluteUri ?? service?.ConnectedOrgFriendlyName);

                    if (service.IsReady)
                    {
                        //Delete everything
                        Console.BackgroundColor = ConsoleColor.DarkRed;
                        Console.WriteLine(Environment.NewLine + "-----DELETING ALL QUESTIONNAIRE DATA-----" + Environment.NewLine + ":)");

                        CrmSdkHelper.DeleteQuestionnaireData(service);

                        Console.WriteLine("-----QUESTIONNAIRE DATA DELETED-----");
                    }
                    else
                    {
                        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)
            {
                CrmSdkHelper.HandleException(ex);
            }
            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }
            }
        }
Esempio n. 14
0
        public static void ETLQuestionnaireData(Questionnaire questionnaireData, CrmServiceClient existingService = null, string outputPath = "general.integration.js")
        {
            CrmServiceClient service = null;

            try
            {
                service = CrmSdkHelper.Connect();

                if (service != null)
                {
                    Console.BackgroundColor = ConsoleColor.DarkGreen;

                    Console.WriteLine("Connected to the organization server for " + service?.CrmConnectOrgUriActual?.AbsoluteUri ?? service?.ConnectedOrgFriendlyName);

                    if (service.IsReady)
                    {
                        Console.BackgroundColor = ConsoleColor.DarkGreen;
                        Console.WriteLine(Environment.NewLine + "-----CREATING QUESTIONNAIRE DATA-----" + Environment.NewLine + ":)");

                        CrmSdkHelper.CreateOrUpdateCrmWithExcelData(ref service, questionnaireData);

                        Console.WriteLine("-----QUESTIONNAIRE DATA SAVED-----");
                    }
                    else
                    {
                        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)
            {
                CrmSdkHelper.HandleException(ex);
            }
            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }
            }
        }
Esempio n. 15
0
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: dispose managed state (managed objects).
                    _crmClient.Dispose();
                }
                _orgService = null;


                disposedValue = true;
            }
        }
Esempio n. 16
0
        static void Main(string[] args)
        {
            var connectionString     = @"ServiceUri=https://myorg.crmdomain.ru:444/myorg; AuthType=IFD; Domain=crmdomain; UserName=crmdomain\crmuser; Password=mypassword; LoginPrompt=Never; RequireNewInstance=True;";
            CrmServiceClient service = new CrmServiceClient(connectionString);

            var app = new Program(service);

            var timer = new Timer(3000);

            timer.Elapsed += app.Do;
            timer.Start();

            Console.ReadKey();
            timer.Stop();
            service.Dispose();
        }
        static void Main()
        {
            // The connection to the Organization web service.
            CrmServiceClient serviceClient = null;
            OrganizationServiceManager serviceManager;
            
            int timeoutInMinutes = int.Parse(ConfigurationManager.AppSettings["TimeoutInMinutes"]);
            int defaultConnectionLimit = int.Parse(ConfigurationManager.AppSettings["DefaultConnectionLimit"]);

            // Allows .NET to run multiple threads https://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.defaultconnectionlimit(v=vs.110).aspx
            System.Net.ServicePointManager.DefaultConnectionLimit = defaultConnectionLimit;

            try
            {
                // Establish an authenticated connection to Crm.
                string connectionString = ConfigurationManager.ConnectionStrings["CrmConnect"].ConnectionString;
                
                CrmServiceClient.MaxConnectionTimeout = new TimeSpan(0, timeoutInMinutes, 0);
                serviceClient = new CrmServiceClient(connectionString);          
                serviceManager = new OrganizationServiceManager(serviceClient);

                LogAppSettings(); // Display App Settings
                DetermineOperationType(serviceClient, serviceManager);
               
                Console.WriteLine();
                Console.WriteLine("Completed!");
            }
            catch (FaultException<OrganizationServiceFault> e) { HandleException(e); }
            catch (TimeoutException e) { HandleException(e); }
            catch (SecurityTokenValidationException e) { HandleException(e); }
            catch (ExpiredSecurityTokenException e) { HandleException(e); }
            catch (MessageSecurityException e) { HandleException(e); }
            catch (SecurityNegotiationException e) { HandleException(e); }
            catch (SecurityAccessDeniedException e) { HandleException(e); }
            catch (FormatException e) { HandleException(e); }
            catch (InvalidOperationException e) { HandleException(e); }
            catch (Exception e) { HandleException(e); }

            finally
            {
                // Always dispose the service object to close the service connection and free resources.
                if (serviceClient != null) serviceClient.Dispose();

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Esempio n. 18
0
        public void Module2LabCAsUnitTest(string name, string line1, string city)
        {
            var cnString         = ConfigurationManager.ConnectionStrings["CrmOnline"].ConnectionString;
            var crmServiceClient = new CrmServiceClient(cnString);

            var account = new Entity("account");

            account["name"]           = name;
            account["address1_line1"] = line1;
            account["address1_city"]  = city;

            var newAccountGuid = crmServiceClient.Create(account);

            Debug.WriteLine($"New account id: {newAccountGuid}");

            crmServiceClient.Dispose();
        }
Esempio n. 19
0
        public static void DeleteLegislation(CrmServiceClient existingService = null)
        {
            var doNotDispose = existingService != null ? true : false;

            CrmServiceClient service = null;

            try
            {
                service = existingService == null?CrmSdkHelper.Connect() : existingService;

                if (service.IsReady)
                {
                    Console.BackgroundColor = ConsoleColor.DarkRed;
                    Console.WriteLine("-----DELETING ANY EXISTING LEGISTLATION DATA-----");

                    CrmSdkHelper.DeleteLegislation(service);

                    Console.WriteLine("-----LEGISLATION DATA DELETED-----");
                }
                else
                {
                    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)
            {
                CrmSdkHelper.HandleException(ex);
            }
            finally
            {
                if (service != null && !doNotDispose)
                {
                    service.Dispose();
                }
            }
        }
        static CrmServiceClient conn = null;                 // Invocamos la Conexión y creamos el campo conn*, la variable conn es de tipo crmServiceClient, solo hay una copia de cada campo estático

        public static IOrganizationService ObtenerConexion() // Método estático, del tipo organization services
        {
            try
            {
                // Utilizamos el metodo string.format() , convierte el valor de los objetos a string en el formato deseado
                connection = string.Format(ConfigurationManager.AppSettings["Connection_CRM"], urlCRM, usuarioCRM, claveCRM);

                // Output: "Url={0}; Username={1};Password={2};AuthType=Office365;RequireNewInstance=True;"

                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                // Definicion del protocolo de seguridad de la capa de transporte

                // Credenciales para conectarse a la instancia especifica de CRM online
                conn = new CrmServiceClient(connection); // con connection entregamos los parametros de conexión formateadas anteriormente

                // Entregamos la conexión formateada

                //Validamos si se pudo realizar la Conexión
                if (conn.IsReady)
                {
                    _orgService = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService) // respondio datos o fue null
                                  conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy; // set up de la variable
                    conn.Dispose();                                                                                      // Definida en la Interface Disposable ( desechar), su funcion es Liberar Recursos
                    conn = null;                                                                                         // reasignamos la variable a null
                    return(_orgService);                                                                                 // retornamos la conexión
                }
                else
                {
                    conn.Dispose();
                    conn = null;
                    return(_orgService);
                }
            }
            catch (Exception ex)
            {
                // Implementación del DLL
                // Guarda en la variable ruta, La ruta de registro del servicio
                string ruta = ConfigurationManager.AppSettings["PathLogServicio"];
                // Utiliza el .dll ZthMetodosVarios
                ZthMetodosVarios.Metodos.GuardarLog(ruta, "Se ha producido el siguiente error: " + ex.Message.ToString());
                // Guarda el registro en ruta; Se ha producido el siguiente error + el mensaje que arroja la excepción
                throw new Exception(ex.Message.ToString());
            }
        }
Esempio n. 21
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
                    var query = new QueryExpression
                    {
                        EntityName = Role.EntityLogicalName,
                        ColumnSet  = new ColumnSet("name", "roleid")
                    };

                    EntityCollection entities = service.RetrieveMultiple(query);
                    // Write the name and ID of each role to the console.
                    foreach (Entity item in entities.Entities)
                    {
                        Role role = item.ToEntity <Role>();
                        Console.WriteLine("Name: {0}. Id: {1}", role.Name, role.Id);
                    }


                    #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. 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

                    // Get the current user's information.
                    WhoAmIRequest  userRequest  = new WhoAmIRequest();
                    WhoAmIResponse userResponse = (WhoAmIResponse)service.Execute(userRequest);

                    // Retrieve the working hours of the current user.
                    QueryScheduleRequest scheduleRequest = new QueryScheduleRequest
                    {
                        ResourceId = userResponse.UserId,
                        Start      = DateTime.Now,
                        End        = DateTime.Today.AddDays(7),
                        TimeCodes  = new TimeCode[] { TimeCode.Available }
                    };
                    QueryScheduleResponse scheduleResponse = (QueryScheduleResponse)service.Execute(scheduleRequest);

                    // Verify if some data is returned for the availability of the current user
                    if (scheduleResponse.TimeInfos.Length > 0)
                    {
                        Console.WriteLine("Successfully queried the working hours of the current user.");
                    }
                }
                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;
                    }
                }
            }
            #endregion Demonstrate


            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 != null)
                {
                    // Service implements IOrganizationService interface
                    if (service.IsReady)
                    {
                        #region Sample Code
                        //////////////////////////////////////////////
                        #region Demonstrate

                        // Instantiate an account object.

                        Entity newAccount = new Entity("account");

                        // Set the required attributes. For account, only the name is required.

                        newAccount["name"] = "Fourth Coffee";

                        //Set any other attribute values.

                        newAccount["address2_postalcode"] = "98074";

                        // Create an account record named Fourth Coffee.

                        Guid accountid = service.Create(newAccount);

                        Console.WriteLine("Created {0} entity named {1}.", newAccount.LogicalName, newAccount["name"]);

                        // Create a column set to define which attributes should be retrieved.
                        ColumnSet attributes = new ColumnSet("name", "ownerid");

                        // Retrieve the account and its name and ownerid attributes.
                        newAccount = service.Retrieve(newAccount.LogicalName, accountid, attributes);

                        Console.WriteLine("Retrieved Entity");

                        /*
                         * IMPORTANT:
                         * Do not update an entity using a retrieved entity instance.
                         * Always instantiate a new Entity and
                         * set the primary key value to match the entity you want to update.
                         * Only set the attribute values you are changing.
                         */

                        Entity accountToUpdate = new Entity("account");
                        accountToUpdate["accountid"] = newAccount.Id;

                        // Update the address 1 postal code attribute.
                        accountToUpdate["address1_postalcode"] = "98052";

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

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

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

                        // Perform the update.
                        service.Update(accountToUpdate);

                        Console.WriteLine("Updated Entity");

                        //Delete the entity
                        service.Delete("account", accountid);

                        Console.WriteLine("Deleted Entity");

                        #endregion Demonstrate
                        //////////////////////////////////////////////
                        #endregion Sample Code

                        Console.WriteLine("The sample completed successfully");
                        return;
                    }
                    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. 24
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 revenue metric, setting the Amount Data Type to 'Money'
                    // and the Metric Type to 'Amount'.
                    Metric sampleMetric = new Metric()
                    {
                        Name           = "Sample Revenue Metric",
                        AmountDataType = new OptionSetValue(0),
                        IsAmount       = true,
                    };
                    _metricId       = service.Create(sampleMetric);
                    sampleMetric.Id = _metricId;

                    Console.Write("Created revenue metric, ");

                    #region Create RollupFields

                    // Create RollupField which targets the actual totals.
                    RollupField actual = new RollupField()
                    {
                        SourceEntity           = SalesOrder.EntityLogicalName,
                        SourceAttribute        = "totalamount",
                        GoalAttribute          = "actualmoney",
                        SourceState            = 1,
                        EntityForDateAttribute = SalesOrder.EntityLogicalName,
                        DateAttribute          = "datefulfilled",
                        MetricId = sampleMetric.ToEntityReference()
                    };
                    _actualId = service.Create(actual);

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

                    #endregion

                    #region Create the goal rollup query

                    // The query locates sales orders in the first sales
                    // representative's area (zip code: 60661) and with a value
                    // greater than $1,000.
                    GoalRollupQuery goalRollupQuery = new GoalRollupQuery()
                    {
                        Name            = "First Example Goal Rollup Query",
                        QueryEntityType = SalesOrder.EntityLogicalName,
                        FetchXml        = @"<fetch mapping=""logical"" version=""1.0""><entity name=""salesorder""><attribute name=""customerid"" /><attribute name=""name"" /><attribute name=""salesorderid"" /><attribute name=""statuscode"" /><attribute name=""totalamount"" /><order attribute=""name"" /><filter><condition attribute=""totalamount"" operator=""gt"" value=""1000"" /><condition attribute=""billto_postalcode"" operator=""eq"" value=""60661"" /></filter></entity></fetch>"
                    };
                    _rollupQueryId     = service.Create(goalRollupQuery);
                    goalRollupQuery.Id = _rollupQueryId;

                    Console.Write("created rollup query.");
                    Console.WriteLine();

                    #endregion

                    #region Create two goals: one parent and one child goal

                    // Create the parent goal.
                    Goal parentGoal = new Goal()
                    {
                        Title = "Parent Goal Example",
                        RollupOnlyFromChildGoals = true,
                        TargetMoney        = new Money(1000.0M),
                        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)
                    };
                    _parentGoalId = service.Create(parentGoal);
                    parentGoal.Id = _parentGoalId;

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

                    // Create the child goal.
                    Goal firstChildGoal = new Goal()
                    {
                        Title = "First Child Goal Example",
                        ConsiderOnlyGoalOwnersRecords = true,
                        TargetMoney        = new Money(1000.0M),
                        IsFiscalPeriodGoal = false,
                        MetricId           = sampleMetric.ToEntityReference(),
                        ParentGoalId       = parentGoal.ToEntityReference(),
                        GoalOwnerId        = new EntityReference
                        {
                            Id          = _salesRepresentativeId,
                            LogicalName = SystemUser.EntityLogicalName
                        },
                        OwnerId = new EntityReference
                        {
                            Id          = _salesManagerId,
                            LogicalName = SystemUser.EntityLogicalName
                        },
                        RollUpQueryActualMoneyId = goalRollupQuery.ToEntityReference(),
                        GoalStartDate            = DateTime.Today.AddDays(-1),
                        GoalEndDate = DateTime.Today.AddDays(30)
                    };
                    _firstChildGoalId = service.Create(firstChildGoal);

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

                    #endregion

                    // Calculate roll-up of goals.
                    // Note: Recalculate can be run against any goal in the tree to cause
                    // a rollup of the whole tree.
                    RecalculateRequest recalculateRequest = new RecalculateRequest()
                    {
                        Target = parentGoal.ToEntityReference()
                    };
                    service.Execute(recalculateRequest);

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

                    // Retrieve and report 3 different computed values for the goals
                    // - Percentage
                    // - ComputedTargetAsOfTodayPercentageAchieved
                    // - ComputedTargetAsOfTodayMoney
                    QueryExpression retrieveValues = new QueryExpression()
                    {
                        EntityName = Goal.EntityLogicalName,
                        ColumnSet  = new ColumnSet(
                            "title",
                            "computedtargetasoftodaypercentageachieved",
                            "computedtargetasoftodaymoney")
                    };
                    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("ComputedTargetAsOfTodayPercentageAchieved: {0}",
                                          temp.ComputedTargetAsOfTodayPercentageAchieved);
                        Console.WriteLine("ComputedTargetAsOfTodayMoney: {0}",
                                          temp.ComputedTargetAsOfTodayMoney.Value);
                        Console.WriteLine("<End of Listing>");
                    }


                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                #endregion Demonstrate
                #endregion Sample Code

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

            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 column set object that indicates the fields to be retrieved.
                    var columns = new ColumnSet(
                        "contactid",
                        "firstname",
                        "lastname",
                        "jobtitle");

                    // Retrieve the contact using the ID of the record that was just created.
                    // The EntityLogicalName indicates the EntityType of the object being retrieved.
                    var contact = (Contact)service.Retrieve(
                        Contact.EntityLogicalName, _contactId, columns);

                    Console.WriteLine("The contact for the sample has been retrieved.");

                    // Serialize the contact into XML and write it to the hard drive.
                    var earlyBoundSerializer = new DataContractSerializer(typeof(Contact));

                    // Create a unique file name for the XML.
                    String earlyboundFile = "Contact_early_" + contact.ContactId.Value.ToString("B") + ".xml";

                    // Write the serialized object to a file.  The using statement will
                    // ensure that the FileStream is disposed of correctly.  The FileMode
                    // will ensure that the file is overwritten if it already exists.
                    using (var file = new FileStream(earlyboundFile, FileMode.Create))
                    {
                        // Write the XML to disk.
                        earlyBoundSerializer.WriteObject(file, contact);
                    }

                    Console.WriteLine(
                        "The early-bound contact instance has been serialized to a file, {0}.",
                        earlyboundFile);

                    // Convert the contact to a late-bound entity instance and serialize it to disk.
                    var    lateboundContact = contact.ToEntity <Entity>();
                    String lateboundFile    = "Contact_late_" + lateboundContact.Id.ToString("B") + ".xml";

                    var lateBoundSerializer = new DataContractSerializer(typeof(Entity));
                    // Write the serialized object to a file.
                    using (var file = new FileStream(lateboundFile, FileMode.Create))
                    {
                        lateBoundSerializer.WriteObject(file, lateboundContact);
                    }

                    Console.WriteLine(
                        "The late-bound contact instance has been serialized to a file, {0}.",
                        lateboundFile);
                    Contact deserializedContact = null;
                    using (var file = new FileStream(earlyboundFile, FileMode.Open))
                    {
                        deserializedContact = (Contact)earlyBoundSerializer.ReadObject(file);
                        Console.WriteLine("The contact has been de-serialized: {0} {1}",
                                          deserializedContact.FirstName, deserializedContact.LastName);
                    }

                    // Update the contact to prove that the de-serialization worked.
                    deserializedContact.JobTitle = "Plumber";
                    service.Update(deserializedContact);

                    Console.WriteLine("The contact was 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. 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
                    // Grab all Solution Components for a solution.
                    QueryByAttribute componentQuery = new QueryByAttribute
                    {
                        EntityName = SolutionComponent.EntityLogicalName,
                        ColumnSet  = new ColumnSet("componenttype", "objectid", "solutioncomponentid", "solutionid"),
                        Attributes = { "solutionid" },

                        // In your code, this value would probably come from another query.
                        Values = { _primarySolutionId }
                    };

                    IEnumerable <SolutionComponent> allComponents =
                        service.RetrieveMultiple(componentQuery).Entities.Cast <SolutionComponent>();

                    foreach (SolutionComponent component in allComponents)
                    {
                        // For each solution component, retrieve all dependencies for the component.
                        RetrieveDependentComponentsRequest dependentComponentsRequest =
                            new RetrieveDependentComponentsRequest
                        {
                            ComponentType = component.ComponentType.Value,
                            ObjectId      = component.ObjectId.Value
                        };
                        RetrieveDependentComponentsResponse dependentComponentsResponse =
                            (RetrieveDependentComponentsResponse)service.Execute(dependentComponentsRequest);

                        // If there are no dependent components, we can ignore this component.
                        if (dependentComponentsResponse.EntityCollection.Entities.Any() == false)
                        {
                            continue;
                        }

                        // If there are dependencies upon this solution component, and the solution
                        // itself is managed, then you will be unable to delete the solution.
                        Console.WriteLine("Found {0} dependencies for Component {1} of type {2}",
                                          dependentComponentsResponse.EntityCollection.Entities.Count,
                                          component.ObjectId.Value,
                                          component.ComponentType.Value
                                          );
                        //A more complete report requires more code
                        foreach (Dependency d in dependentComponentsResponse.EntityCollection.Entities)
                        {
                            DependencyReport(service, d);
                        }
                    }

                    //Find out if any dependencies on a  specific global option set would prevent it from being deleted
                    // 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);
                    _globalOptionSetId = retrieveOptionSetResponse.OptionSetMetadata.MetadataId;
                    if (_globalOptionSetId != null)
                    {
                        //Use the global OptionSet MetadataId with the appropriate componenttype
                        // to call RetrieveDependenciesForDeleteRequest
                        RetrieveDependenciesForDeleteRequest retrieveDependenciesForDeleteRequest = new RetrieveDependenciesForDeleteRequest
                        {
                            ComponentType = (int)componenttype.OptionSet,
                            ObjectId      = (Guid)_globalOptionSetId
                        };

                        RetrieveDependenciesForDeleteResponse retrieveDependenciesForDeleteResponse =
                            (RetrieveDependenciesForDeleteResponse)service.Execute(retrieveDependenciesForDeleteRequest);
                        Console.WriteLine("");
                        foreach (Dependency d in retrieveDependenciesForDeleteResponse.EntityCollection.Entities)
                        {
                            if (d.DependentComponentType.Value == 2)//Just testing for Attributes
                            {
                                String attributeLabel = "";
                                RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest
                                {
                                    MetadataId = (Guid)d.DependentComponentObjectId
                                };
                                RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);

                                AttributeMetadata attmet = retrieveAttributeResponse.AttributeMetadata;

                                attributeLabel = attmet.DisplayName.UserLocalizedLabel.Label;

                                Console.WriteLine("An {0} named {1} will prevent deleting the {2} global option set.",
                                                  (componenttype)d.DependentComponentType.Value,
                                                  attributeLabel,
                                                  _globalOptionSetName);
                            }
                        }
                    }

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

                    //DeleteRequiredRecords(promptForDelete);
                }
                #endregion Demonstrate
                #endregion Sample Code

                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;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

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

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Esempio n. 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

                    // The custom prefix would typically be passed in as an argument or
                    // determined by the publisher of the custom solution.
                    String prefix = "new_";

                    String customEntityName = prefix + "sampleentity";

                    // Create the custom activity entity.
                    CreateEntityRequest request = new CreateEntityRequest
                    {
                        HasNotes         = true,
                        HasActivities    = false,
                        PrimaryAttribute = new StringAttributeMetadata
                        {
                            SchemaName    = "Subject",
                            RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                            MaxLength     = 100,
                            DisplayName   = new Microsoft.Xrm.Sdk.Label("Subject", 1033)
                        },
                        Entity = new EntityMetadata
                        {
                            IsActivity            = true,
                            SchemaName            = customEntityName,
                            DisplayName           = new Microsoft.Xrm.Sdk.Label("Sample Entity", 1033),
                            DisplayCollectionName = new Microsoft.Xrm.Sdk.Label("Sample Entity", 1033),
                            OwnershipType         = OwnershipTypes.UserOwned,
                            IsAvailableOffline    = true,
                        }
                    };

                    service.Execute(request);

                    //Entity must be published

                    // Add few attributes to the custom activity entity.
                    CreateAttributeRequest fontFamilyAttributeRequest =
                        new CreateAttributeRequest
                    {
                        EntityName = customEntityName,
                        Attribute  = new StringAttributeMetadata
                        {
                            SchemaName  = prefix + "fontfamily",
                            DisplayName = new Microsoft.Xrm.Sdk.Label("Font Family", 1033),
                            MaxLength   = 100
                        }
                    };
                    CreateAttributeResponse fontFamilyAttributeResponse =
                        (CreateAttributeResponse)service.Execute(
                            fontFamilyAttributeRequest);

                    CreateAttributeRequest fontColorAttributeRequest =
                        new CreateAttributeRequest
                    {
                        EntityName = customEntityName,
                        Attribute  = new StringAttributeMetadata
                        {
                            SchemaName  = prefix + "fontcolor",
                            DisplayName = new Microsoft.Xrm.Sdk.Label("Font Color", 1033),
                            MaxLength   = 50
                        }
                    };
                    CreateAttributeResponse fontColorAttributeResponse =
                        (CreateAttributeResponse)service.Execute(
                            fontColorAttributeRequest);

                    CreateAttributeRequest fontSizeAttributeRequest =
                        new CreateAttributeRequest
                    {
                        EntityName = customEntityName,
                        Attribute  = new IntegerAttributeMetadata
                        {
                            SchemaName  = prefix + "fontSize",
                            DisplayName = new Microsoft.Xrm.Sdk.Label("Font Size", 1033)
                        }
                    };
                    CreateAttributeResponse fontSizeAttributeResponse =
                        (CreateAttributeResponse)service.Execute(
                            fontSizeAttributeRequest);

                    Console.WriteLine("The custom activity has been created.");

                    #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();
            }
        }
Esempio n. 28
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 three e-mail attachments
                    for (int i = 0; i < 3; i++)
                    {
                        ActivityMimeAttachment _sampleAttachment = new ActivityMimeAttachment
                        {
                            ObjectId       = new EntityReference(Email.EntityLogicalName, emailId),
                            ObjectTypeCode = Email.EntityLogicalName,
                            Subject        = String.Format("Sample Attachment {0}", i),
                            Body           = System.Convert.ToBase64String(
                                new ASCIIEncoding().GetBytes("Example Attachment")),
                            FileName = String.Format("ExampleAttachment{0}.txt", i)
                        };

                        emailAttachmentId[i] = service.Create(_sampleAttachment);
                    }

                    Console.WriteLine("Created three e-mail attachments for the e-mail activity.");

                    // Retrieve an attachment including its id, subject, filename and body.
                    ActivityMimeAttachment _singleAttachment =
                        (ActivityMimeAttachment)service.Retrieve(
                            ActivityMimeAttachment.EntityLogicalName,
                            emailAttachmentId[0],
                            new ColumnSet("activitymimeattachmentid",
                                          "subject",
                                          "filename",
                                          "body"));

                    Console.WriteLine("Retrieved an email attachment, {0}.", _singleAttachment.FileName);

                    // Update attachment
                    _singleAttachment.FileName = "ExampleAttachmentUpdated.txt";
                    service.Update(_singleAttachment);

                    Console.WriteLine("Updated the retrieved e-mail attachment to {0}.", _singleAttachment.FileName);

                    // Retrieve all attachments associated with the email activity.
                    QueryExpression _attachmentQuery = new QueryExpression
                    {
                        EntityName = ActivityMimeAttachment.EntityLogicalName,
                        ColumnSet  = new ColumnSet("activitymimeattachmentid"),
                        Criteria   = new FilterExpression
                        {
                            Conditions =
                            {
                                new ConditionExpression
                                {
                                    AttributeName = "objectid",
                                    Operator      = ConditionOperator.Equal,
                                    Values        = { emailId }
                                },
                                new ConditionExpression
                                {
                                    AttributeName = "objecttypecode",
                                    Operator      = ConditionOperator.Equal,
                                    Values        = { Email.EntityLogicalName }
                                }
                            }
                        }
                    };

                    EntityCollection results = service.RetrieveMultiple(
                        _attachmentQuery);

                    Console.WriteLine("Retrieved all the e-mail attachments.");

                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                #endregion Demonstrate
                #endregion Sample Code
                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;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

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

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

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

                    // Processes the data in newsampleproduct.xml
                    // to represent new products. Creates 13 records in sample_product entity.
                    // RecordCreated property returns true to indicate the records were created.

                    ProcessUpsert(service, ".\\newsampleproduct.xml");

                    // Processes the data in updatedsampleproduct.xml
                    // to represent updates to products previously created.
                    // Updates 6 existing records in sample_product entity.
                    // RecordCreated property returns false to indicate the existing records were updated.
                    ProcessUpsert(service, ".\\updatedsampleproduct.xml");

                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                    Console.WriteLine("The sample completed successfully");
                    return;
                }
                #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. 30
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

                    Console.WriteLine("Enabling auditing on the organization and account entities.");

                    // Enable auditing on the organization.
                    // First, get the organization's ID from the system user record.
                    Guid orgId = ((WhoAmIResponse)service.Execute(new WhoAmIRequest())).OrganizationId;

                    // Next, retrieve the organization's record.
                    var org = service.Retrieve(Organization.EntityLogicalName, orgId,
                                               new ColumnSet(new string[] { "organizationid", "isauditenabled" })) as Organization;

                    // Finally, enable auditing on the organization.
                    bool organizationAuditingFlag = org.IsAuditEnabled.Value;
                    org.IsAuditEnabled = true;
                    service.Update(org);

                    // Enable auditing on account entities.
                    bool accountAuditingFlag = EnableEntityAuditing(service, Account.EntityLogicalName, true);
                    #endregion Enable Auditing for an Account
                    #region Retrieve the Record Change History
                    Console.WriteLine("Retrieving the account change history.\n");

                    // Retrieve the audit history for the account and display it.
                    var changeRequest = new RetrieveRecordChangeHistoryRequest();
                    changeRequest.Target = new EntityReference(Account.EntityLogicalName, _newAccountId);

                    var changeResponse =
                        (RetrieveRecordChangeHistoryResponse)service.Execute(changeRequest);

                    AuditDetailCollection details = changeResponse.AuditDetailCollection;

                    foreach (AttributeAuditDetail detail in details.AuditDetails)
                    {
                        // Display some of the detail information in each audit record.
                        DisplayAuditDetails(service, detail);
                    }
                    #endregion Retrieve the Record Change History

                    #region Retrieve the Attribute Change History

                    // Update the Telephone1 attribute in the Account entity record.
                    var accountToUpdate = new Account();
                    accountToUpdate.AccountId  = _newAccountId;
                    accountToUpdate.Telephone1 = "123-555-5555";
                    service.Update(accountToUpdate);
                    Console.WriteLine("Updated the Telephone1 field in the Account entity.");

                    // Retrieve the attribute change history.
                    Console.WriteLine("Retrieving the attribute change history for Telephone1.");
                    var attributeChangeHistoryRequest = new RetrieveAttributeChangeHistoryRequest
                    {
                        Target = new EntityReference(
                            Account.EntityLogicalName, _newAccountId),
                        AttributeLogicalName = "telephone1"
                    };

                    var attributeChangeHistoryResponse =
                        (RetrieveAttributeChangeHistoryResponse)service.Execute(attributeChangeHistoryRequest);

                    // Display the attribute change history.
                    details = attributeChangeHistoryResponse.AuditDetailCollection;

                    foreach (var detail in details.AuditDetails)
                    {
                        DisplayAuditDetails(service, detail);
                    }

                    // Save an Audit record ID for later use.
                    Guid auditSampleId = details.AuditDetails.First().AuditRecord.Id;
                    #endregion Retrieve the Attribute Change History

                    #region Retrieve the Audit Details
                    Console.WriteLine("Retrieving audit details for an audit record.");

                    // Retrieve the audit details and display them.
                    var auditDetailsRequest = new RetrieveAuditDetailsRequest
                    {
                        AuditId = auditSampleId
                    };

                    var auditDetailsResponse =
                        (RetrieveAuditDetailsResponse)service.Execute(auditDetailsRequest);
                    DisplayAuditDetails(service, auditDetailsResponse.AuditDetail);

                    #endregion Retrieve the Audit Details

                    #region Revert Auditing
                    // Set the organization and account auditing flags back to the old values
                    org.IsAuditEnabled = organizationAuditingFlag;
                    service.Update(org);

                    EnableEntityAuditing(service, Account.EntityLogicalName, accountAuditingFlag);

                    #endregion Revert Auditing

                    #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;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

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

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