Ejemplo n.º 1
0
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            // Get the current user.
            WhoAmIRequest  userRequest  = new WhoAmIRequest();
            WhoAmIResponse userResponse = (WhoAmIResponse)service.Execute(userRequest);

            _userId = userResponse.UserId;

            // Create the activity party for sending and receiving the fax.
            ActivityParty party = new ActivityParty
            {
                PartyId = new EntityReference(SystemUser.EntityLogicalName, _userId)
            };

            // Create the fax object.
            Fax fax = new Fax
            {
                Subject = "Sample Fax",
                From    = new ActivityParty[] { party },
                To      = new ActivityParty[] { party }
            };

            _faxId = service.Create(fax);
            Console.WriteLine("Created a fax: '{0}'.", fax.Subject);
        }
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Creates the email activity.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            var            userRequest = new WhoAmIRequest();
            WhoAmIResponse user        = (WhoAmIResponse)service.Execute(userRequest);

            // Current user.
            _myUserId = user.UserId;

            // Query to retrieve other users.
            var querySystemUser = new QueryExpression
            {
                EntityName = SystemUser.EntityLogicalName,
                ColumnSet  = new ColumnSet(new String[] { "systemuserid", "fullname" }),
                Criteria   = new FilterExpression()
            };

            querySystemUser.Criteria.AddCondition("businessunitid",
                                                  ConditionOperator.Equal, user.BusinessUnitId);
            querySystemUser.Criteria.AddCondition("systemuserid",
                                                  ConditionOperator.NotEqual, _myUserId);
            // Excluding SYSTEM user.
            querySystemUser.Criteria.AddCondition("lastname",
                                                  ConditionOperator.NotEqual, "SYSTEM");
            // Excluding INTEGRATION user.
            querySystemUser.Criteria.AddCondition("lastname",
                                                  ConditionOperator.NotEqual, "INTEGRATION");

            DataCollection <Entity> otherUsers = service.RetrieveMultiple(
                querySystemUser).Entities;

            int count = service.RetrieveMultiple(querySystemUser).Entities.Count;

            if (count > 0)
            {
                _otherUserId = (Guid)otherUsers[count - 1].Attributes["systemuserid"];

                Console.WriteLine("Retrieved new owner {0} for assignment.",
                                  otherUsers[count - 1].Attributes["fullname"]);
            }
            else
            {
                throw new FaultException(
                          "No other user found in the current business unit for assignment.");
            }

            // Create an Account record
            Account newAccount = new Account
            {
                Name = "Example Account"
            };

            _accountId = service.Create(newAccount);
            Console.WriteLine("Created {0}", newAccount.Name);

            return;
        }
Ejemplo n.º 3
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            // Get the current user's information.
            WhoAmIRequest  userRequest  = new WhoAmIRequest();
            WhoAmIResponse userResponse = (WhoAmIResponse)service.Execute(userRequest);

            _currentUserId = userResponse.UserId;

            // Create another user, Kevin Cook.
            _otherUserId = SystemUserProvider.RetrieveSalesManager(service);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            // Create a contact to send an email to (To: field)
            Contact emailContact = new Contact
            {
                FirstName     = "David",
                LastName      = "Pelton",
                EMailAddress1 = "*****@*****.**",
                DoNotEMail    = false
            };

            _contactId = service.Create(emailContact);
            Console.WriteLine("Created a sample contact.");

            // Get a system user to send the email (From: field)
            WhoAmIRequest  systemUserRequest  = new WhoAmIRequest();
            WhoAmIResponse systemUserResponse = (WhoAmIResponse)service.Execute(systemUserRequest);

            _userId = systemUserResponse.UserId;
        }
Ejemplo n.º 5
0
        public static WhoAmIResponse WhoAmI(HttpClient client)
        {
            WhoAmIResponse returnValue = new WhoAmIResponse();
            //Send the WhoAmI request to the Web API using a GET request.
            HttpResponseMessage response = client.GetAsync("WhoAmI",
                                                           HttpCompletionOption.ResponseHeadersRead).Result;

            if (response.IsSuccessStatusCode)
            {
                //Get the response content and parse it.
                JObject body = JObject.Parse(response.Content.ReadAsStringAsync().Result);
                returnValue.BusinessUnitId = (Guid)body["BusinessUnitId"];
                returnValue.UserId         = (Guid)body["UserId"];
                returnValue.OrganizationId = (Guid)body["OrganizationId"];
            }
            else
            {
                throw new Exception(string.Format("The WhoAmI request failed with a status of '{0}'",
                                                  response.ReasonPhrase));
            }
            return(returnValue);
        }
Ejemplo n.º 6
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();
            }
        }
Ejemplo n.º 7
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 Setup
                    #region Demonstrate
                    // Create a contact to send an email to (To: field)
                    Contact emailContact = new Contact()
                    {
                        FirstName     = "Lisa",
                        LastName      = "Andrews",
                        EMailAddress1 = "*****@*****.**"
                    };
                    _contactId = service.Create(emailContact);
                    Console.WriteLine("Created a sample contact.");

                    // Get a system user to send the email (From: field)
                    WhoAmIRequest  systemUserRequest  = new WhoAmIRequest();
                    WhoAmIResponse systemUserResponse = (WhoAmIResponse)service.Execute(systemUserRequest);

                    ColumnSet  cols        = new ColumnSet("internalemailaddress");
                    SystemUser emailSender = (SystemUser)service.Retrieve(SystemUser.EntityLogicalName, systemUserResponse.UserId, cols);


                    // Create the request.
                    DeliverPromoteEmailRequest deliverEmailRequest = new DeliverPromoteEmailRequest
                    {
                        Subject     = "SDK Sample Email",
                        To          = emailContact.EMailAddress1,
                        From        = emailSender.InternalEMailAddress,
                        Bcc         = String.Empty,
                        Cc          = String.Empty,
                        Importance  = "high",
                        Body        = "This message will create an email activity.",
                        MessageId   = Guid.NewGuid().ToString(),
                        SubmittedBy = "",
                        ReceivedOn  = DateTime.Now
                    };

                    // We won't attach a file to the email, but the Attachments property is required.
                    deliverEmailRequest.Attachments            = new EntityCollection(new ActivityMimeAttachment[0]);
                    deliverEmailRequest.Attachments.EntityName = ActivityMimeAttachment.EntityLogicalName;

                    // Execute the request.
                    DeliverPromoteEmailResponse deliverEmailResponse = (DeliverPromoteEmailResponse)service.Execute(deliverEmailRequest);

                    // Verify the success.

                    // Define an anonymous type to define the possible values for
                    // email status
                    var EmailStatus = new
                    {
                        Draft       = 1,
                        Completed   = 2,
                        Sent        = 3,
                        Received    = 3,
                        Canceled    = 5,
                        PendingSend = 6,
                        Sending     = 7,
                        Failed      = 8,
                    };

                    // Query for the delivered email, and verify the status code is "Sent".
                    ColumnSet deliveredMailColumns = new ColumnSet("statuscode");
                    Email     deliveredEmail       = (Email)service.Retrieve(Email.EntityLogicalName, deliverEmailResponse.EmailId, deliveredMailColumns);

                    _emailId = deliveredEmail.ActivityId.Value;

                    if (deliveredEmail.StatusCode.Value == EmailStatus.Sent)
                    {
                        Console.WriteLine("Successfully created and delivered the e-mail message.");
                    }


                    DeleteRequiredRecords(service, prompt);
                }
                #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();
            }
        }
Ejemplo n.º 8
0
        [STAThread] // Added to support UX
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

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

                    // Retrieve the current user information.
                    WhoAmIRequest  whoAmIRequest  = new WhoAmIRequest();
                    WhoAmIResponse whoAmIResponse = (WhoAmIResponse)service.Execute(
                        whoAmIRequest);

                    ColumnSet  columnSet   = new ColumnSet("fullname");
                    SystemUser currentUser = (SystemUser)service.Retrieve(
                        SystemUser.EntityLogicalName,
                        whoAmIResponse.UserId, columnSet);
                    String currentUserName = currentUser.FullName;
                    _userId = currentUser.Id;

                    // Create an instance of an existing queueitem in order to specify
                    // the user that will be working on it using PickFromQueueRequest.

                    PickFromQueueRequest pickFromQueueRequest = new PickFromQueueRequest
                    {
                        QueueItemId = _queueItemId,
                        WorkerId    = _userId
                    };

                    service.Execute(pickFromQueueRequest);

                    Console.WriteLine("The letter queue item is queued for new owner {0}.",
                                      currentUserName);


                    #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();
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Retrieves the requested SystemUser record.  If the record does not exist, a new
        /// Microsoft Dynamics CRM SystemUser record is created and an associated Active
        /// Directory account is created, if it doesn't currently exist.
        /// </summary>
        /// <param name="userName">The username field as set in Microsoft Dynamics CRM</param>
        /// <param name="firstName">The first name of the system user to be retrieved</param>
        /// <param name="lastName">The last name of the system user to be retrieved</param>
        /// <param name="roleStr">The string representing the Microsoft Dynamics CRM security
        /// role for the user</param>
        /// <param name="serviceProxy">The OrganizationServiceProxy object to your Microsoft
        /// Dynamics CRM environment</param>
        /// <param name="ldapPath">The LDAP path for your network - you can either call
        /// ConsolePromptForLDAPPath() to prompt the user or provide a value in code</param>
        /// <returns></returns>
        public static Guid RetrieveSystemUser(String userName, String firstName,
                                              String lastName, String roleStr, CrmServiceClient service,
                                              ref String ldapPath)
        {
            String domain;
            Guid   userId = Guid.Empty;

            if (service == null)
            {
                throw new ArgumentNullException("service");
            }

            if (String.IsNullOrWhiteSpace(userName))
            {
                throw new ArgumentNullException("UserName");
            }

            if (String.IsNullOrWhiteSpace(firstName))
            {
                throw new ArgumentNullException("FirstName");
            }

            if (String.IsNullOrWhiteSpace(lastName))
            {
                throw new ArgumentNullException("LastName");
            }

            // Obtain the current user's information.
            WhoAmIRequest  who           = new WhoAmIRequest();
            WhoAmIResponse whoResp       = (WhoAmIResponse)service.Execute(who);
            Guid           currentUserId = whoResp.UserId;

            SystemUser currentUser =
                service.Retrieve(SystemUser.EntityLogicalName, currentUserId, new ColumnSet("domainname")).ToEntity <SystemUser>();

            // Extract the domain and create the LDAP object.
            String[] userPath = currentUser.DomainName.Split(new char[] { '\\' });
            if (userPath.Length > 1)
            {
                domain = userPath[0] + "\\";
            }
            else
            {
                domain = String.Empty;
            }



            SystemUser existingUser = GetUserIdIfExist(service, domain, userName, firstName, lastName);


            if (existingUser != null)
            {
                userId = existingUser.SystemUserId.Value;

                if (!String.IsNullOrWhiteSpace(roleStr))
                {
                    // Check to make sure the user is assigned the correct role.
                    Role role = RetrieveRoleByName(service, roleStr);

                    // Associate the user with the role when needed.
                    if (!UserInRole(service, userId, role.Id))
                    {
                        AssociateRequest associate = new AssociateRequest()
                        {
                            Target          = new EntityReference(SystemUser.EntityLogicalName, userId),
                            RelatedEntities = new EntityReferenceCollection()
                            {
                                new EntityReference(Role.EntityLogicalName, role.Id)
                            },
                            Relationship = new Relationship("systemuserroles_association")
                        };
                        service.Execute(associate);
                    }
                }
            }
            else
            {
                Console.WriteLine("User Not Found. Manually create user in office 365");
            }

            return(userId);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Creates the email activity.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            WhoAmIRequest  userRequest  = new WhoAmIRequest();
            WhoAmIResponse userResponse = (WhoAmIResponse)service.Execute(userRequest);

            // Create the van resource.
            Equipment van = new Equipment
            {
                Name           = "Van 1",
                TimeZoneCode   = 1,
                BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, userResponse.BusinessUnitId)
            };

            _vanId = service.Create(van);

            Console.WriteLine("Created a sample equipment: {0}.", van.Name);

            // Create the contraints for creating the plumber resource group
            System.Text.StringBuilder builder = new System.Text.StringBuilder("<Constraints>");
            builder.Append("<Constraint>");
            builder.Append("<Expression>");
            builder.Append("<Body>resource[\"Id\"] == ");
            builder.Append(userResponse.UserId.ToString("B"));
            builder.Append(" || resource[\"Id\"] == ");
            builder.Append(_vanId.ToString("B"));
            builder.Append("</Body>");
            builder.Append("<Parameters>");
            builder.Append("<Parameter name=\"resource\" />");
            builder.Append("</Parameters>");
            builder.Append("</Expression>");
            builder.Append("</Constraint>");
            builder.Append("</Constraints>");

            // Define an anonymous type to define the possible constraint based group type code values.
            var ConstraintBasedGroupTypeCode = new
            {
                Static   = 0,
                Dynamic  = 1,
                Implicit = 2
            };
            // Create the plumber resource group.
            ConstraintBasedGroup group = new ConstraintBasedGroup
            {
                BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, userResponse.BusinessUnitId),
                Name           = "Plumber with Van 1",
                Constraints    = builder.ToString(),
                GroupTypeCode  = new OptionSetValue(ConstraintBasedGroupTypeCode.Static),
            };

            _groupId = service.Create(group);

            Console.WriteLine("Created a sample resource group: {0}.", group.Name);

            // Create the resource specification.
            ResourceSpec spec = new ResourceSpec
            {
                BusinessUnitId      = new EntityReference(BusinessUnit.EntityLogicalName, userResponse.BusinessUnitId),
                ObjectiveExpression = @"
                    <Expression>
                        <Body>udf ""Random""(factory,resource,appointment,request,leftoffset,rightoffset)</Body>
                        <Parameters>
                            <Parameter name=""factory"" />
                            <Parameter name=""resource"" />
                            <Parameter name=""appointment"" />
                            <Parameter name=""request"" />
                            <Parameter name=""leftoffset"" />
                            <Parameter name=""rightoffset"" />
                        </Parameters>
                        <Properties EvaluationInterval=""P0D"" evaluationcost=""0"" />
                    </Expression>",
                RequiredCount       = 1,
                Name          = "Test Spec",
                GroupObjectId = _groupId
            };

            _specId = service.Create(spec);

            // Create the plumber required resource object.
            RequiredResource plumberReq = new RequiredResource
            {
                ResourceId     = userResponse.UserId, // assume current user is the plumber
                ResourceSpecId = _specId
            };


            // Create the service for the equipment.
            Service plumberService = new Service
            {
                Name              = "Plumber 1",
                Duration          = 60,
                InitialStatusCode = new OptionSetValue(1),
                Granularity       = "FREQ=MINUTELY;INTERVAL=15;",
                ResourceSpecId    = new EntityReference(ResourceSpec.EntityLogicalName, _specId)
            };

            _plumberServiceId = service.Create(plumberService);

            Console.WriteLine("Created a sample service for the equipment: {0}.", plumberService.Name);

            Console.WriteLine("Required records have been created.");
        }
Ejemplo n.º 11
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Create a queue record.
        /// Create a letter record.
        /// Create a queue item for queue record.
        /// Retrieves new owner's details.
        /// Update the queue item record to assign it to new owner.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            // Create a private queue instance and set its property values.
            Queue newQueue = new Queue
            {
                Name          = "Example Queue.",
                Description   = "This is an example queue.",
                QueueViewType = new OptionSetValue((int)QueueQueueViewType.Private)
            };

            // Create a new queue and store its returned GUID in a variable
            // for later use.
            _queueId = service.Create(newQueue);

            Console.WriteLine("Created {0}.", newQueue.Name);

            Letter newLetter = new Letter
            {
                Description = "Example Letter"
            };

            _letterId = service.Create(newLetter);

            Console.WriteLine("Created {0}.", newLetter.Description);

            // Create a new instance of a queueitem and initialize its
            // properties.
            QueueItem item = new QueueItem
            {
                QueueId  = new EntityReference(Queue.EntityLogicalName, _queueId),
                ObjectId = new EntityReference(Letter.EntityLogicalName, _letterId)
            };

            // Create the queueitem on the server, which will associate
            // the letter with the queue.
            _queueItemId = service.Create(item);

            Console.WriteLine("Created the letter queue item for the queue.");

            // Retrieve the user information.
            WhoAmIRequest  whoAmIRequest  = new WhoAmIRequest();
            WhoAmIResponse whoAmIResponse = (WhoAmIResponse)service.Execute(
                whoAmIRequest);

            ColumnSet  columnSet   = new ColumnSet("fullname");
            SystemUser currentUser = (SystemUser)service.Retrieve(
                SystemUser.EntityLogicalName,
                whoAmIResponse.UserId, columnSet);
            String currentUserName = currentUser.FullName;

            // Create an instance of an existing queueitem in order to specify
            // the user that will be working on it.
            QueueItem queueItem = new QueueItem
            {
                QueueItemId = _queueItemId,
                WorkerId    = new EntityReference(SystemUser.EntityLogicalName,
                                                  whoAmIResponse.UserId)
            };

            service.Update(queueItem);

            Console.WriteLine("The letter queue item is queued for new owner {0}.",
                              currentUserName);

            return;
        }