Esempio n. 1
0
        public CrmConnectionInfo GetConnectionInfo(CrmDbConnection connection)
        {
            var connInfo = _Cache.GetOrAdd(connection.ConnectionString, f =>
            {

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

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

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

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

                return info;

            });

            return connInfo;
        }
Esempio n. 2
0
 public Xrm.SystemUser GetIdentity()
 {
     WhoAmIRequest wai = new WhoAmIRequest();
     var resp = (WhoAmIResponse)_context.Execute(wai);
     var me = _context.SystemUserSet.Where(x => x.Id == resp.UserId).SingleOrDefault();
     return me;
 }
Esempio n. 3
0
        public IOrganizationService GetOrganisationService(OrganizationDetail org, string domain, string userName, string password)
        {

            if (org != null)
            {
                Uri orgServiceUri = null;
                orgServiceUri = new Uri(org.Endpoints[EndpointType.OrganizationService]);
                //if (!string.IsNullOrEmpty(OrganisationServiceHostName))
                //{
                //    UriBuilder builder = new UriBuilder(orgServiceUri);
                //    builder.Host = OrganisationServiceHostName;
                //    orgServiceUri = builder.Uri;
                //}

                IServiceConfiguration<IOrganizationService> orgConfigInfo = ServiceConfigurationFactory.CreateConfiguration<IOrganizationService>(orgServiceUri);

                var creds = _credentialsProvider.GetCredentials(orgConfigInfo.AuthenticationType, domain, userName, password);
                var orgService = new OrganizationServiceProxy(orgConfigInfo, creds);
                orgService.Timeout = new TimeSpan(0, 5, 0);

                var req = new WhoAmIRequest();
                var response = (WhoAmIResponse)orgService.Execute(req);

                Debug.WriteLine(string.Format(" Connected to {0} as Crm user id: {1}", orgConfigInfo.CurrentServiceEndpoint.Address.Uri.ToString(), response.UserId));
                return orgService;
            }
            return null;

        }
Esempio n. 4
0
        public void ProcessWhoAmI()
        {
            WorkAsync("Retrieving your user id...", (w, e) =>
            {
                while (e.Cancel == false)
                {
                    if (w.CancellationPending)
                    {
                        e.Cancel = true;
                    }
                    var request = new WhoAmIRequest();
                    var response = (WhoAmIResponse)Service.Execute(request);

                    e.Result = response.UserId;
                }
            },
                e =>
                {
                    if (!e.Cancelled)
                    {
                        MessageBox.Show(string.Format("You are {0}", (Guid)e.Result));
                    }
                },
                e =>
                {
                    // If progress has to be notified to user, use the following method:
                    //SetWorkingMessage("Message to display");
                },
                null,
                true,
                340,
                150);
        }
 public AppSendEmails(OrganizationServiceProxy service)
 {
     _service = service;
     _wfemailTemp = new ConsoleEmailTemplate(_service);
     WhoAmIRequest requst = new WhoAmIRequest();
     WhoAmIResponse res = (WhoAmIResponse)_service.Execute(requst);
     _userid = res.UserId;
 }
Esempio n. 6
0
        public override WhoAmIRequest.OutputType HandleWhoAmI(WhoAmIRequest.InputType input)
        {
            WhoAmIRequest.OutputType result = new WhoAmIRequest.OutputType();
            result.UserEmailAddress = m_session.Email;
            result.UserIsAnonymous = m_session.IsAnonymous;
            result.UserLogin = m_session.Login;
            result.UserName = m_session.Name;

            return result;
        }
Esempio n. 7
0
        public static void When_a_who_am_i_request_is_invoked_the_caller_id_is_returned()
        {
            var context = new XrmFakedContext();
            context.CallerId = new EntityReference() { Id = Guid.NewGuid(), Name = "Super Faked User" };

            var service = context.GetFakedOrganizationService();
            WhoAmIRequest req = new WhoAmIRequest();

            var response = service.Execute(req) as WhoAmIResponse;
            Assert.Equal(response.UserId, context.CallerId.Id);
        }
Esempio n. 8
0
        /// <summary>
        /// Checks if the "Est. Close Date" is greater than 10 days. If it is,
        /// send an email to the administrator so that s/he can verify close date
        /// with the owner of the opportunity.
        /// </summary>
        protected override void Execute(CodeActivityContext executionContext)
        {
            IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
                IOrganizationServiceFactory serviceFactory =
                    executionContext.GetExtension<IOrganizationServiceFactory>();
                IOrganizationService service =
                    serviceFactory.CreateOrganizationService(context.UserId);

            // Get opportunity entity
            Entity opportunity = service.Retrieve("opportunity", 
                this.inputOpportunity.Get(executionContext).Id, new ColumnSet("estimatedclosedate"));

            // Calulate 10 days from today
            DateTime todayPlusTen = DateTime.UtcNow.AddDays(10.0);

            // Check "Est. Close Date"
            if (opportunity.Contains("estimatedclosedate"))
            {
                DateTime estCloseDate = (DateTime)opportunity["estimatedclosedate"];
                if (DateTime.Compare(estCloseDate, todayPlusTen) > 0)
                {
                    // Need system user id for activity party
                    WhoAmIRequest systemUserRequest = new WhoAmIRequest();
                    WhoAmIResponse systemUser = 
                        (WhoAmIResponse)service.Execute(systemUserRequest);

                    // Create an activity party for the email
                    Entity[] activityParty = new Entity[1];
                    activityParty[0] = new Entity("activityparty");
                    activityParty[0]["partyid"] = 
                        new EntityReference("systemuser", systemUser.UserId);

                    // Create an email message
                    Entity email = new Entity("email");
                    email.LogicalName = "email";
                    email["subject"] = 
                        "Warning: Close date has been extended more than 10 days.";
                    email["description"] = "Verify close date is correct.";
                    email["to"] = activityParty;
                    email["from"] = activityParty;
                    email["regardingobjectid"] = opportunity.ToEntityReference();
                    Guid emailId = service.Create(email);

                    // Send email
                    SendEmailRequest sendEmailRequest = new SendEmailRequest();
                    sendEmailRequest.EmailId = emailId;
                    sendEmailRequest.IssueSend = true;
                    sendEmailRequest.TrackingToken = "";
                    SendEmailResponse sendEmailResponse = 
                        (SendEmailResponse)service.Execute(sendEmailRequest);
                }
            }
        }
        public override WhoAmIRequest.OutputType HandleWhoAmI(WhoAmIRequest.InputType input)
        {
            WhoAmIRequest.OutputType result = new WhoAmIRequest.OutputType();
            result.UserIsAnonymous = WspContext.User == null;
            if (WspContext.User != null)
            {
                result.UserEmailAddress = WspContext.User.Login;
                result.UserLogin = WspContext.User.Login;
                result.UserName = WspContext.User.DisplayName;
            }

            return result;
        }
        /// <summary>
        /// Validate method to attempt to connect to CRM with supplied username/password and then execute a whoami request
        /// </summary>
        /// <param name="username">crm username</param>
        /// <param name="password">crm password</param>
        public override void Validate(string username, string password)
        {
            //get the httpcontext so we can store the user guid for impersonation later
            HttpContext context = HttpContext.Current;

            //if username or password are null, obvs we can't continue
            if (null == username || null == password)
            {
                throw new ArgumentNullException();
            }

            //get the crm connection
            Microsoft.Xrm.Client.CrmConnection connection = CrmUtils.GetCrmConnection(username, password);

            //try the whoami request
            //if it fails (user can't be authenticated, is disabled, etc.), the client will get a soap fault message
            using (OrganizationService service = new OrganizationService(connection))
            {
                try
                {
                    WhoAmIRequest req = new WhoAmIRequest();
                    WhoAmIResponse resp = (WhoAmIResponse)service.Execute(req);
                    Entity systemuser = CrmUtils.GetSystemUser(resp.UserId, service);

                    CrmIdentity crmIdentity = new CrmIdentity();
                    crmIdentity.Name = (string)systemuser["fullname"];
                    crmIdentity.FirstName = (string)systemuser["firstname"];
                    crmIdentity.LastName = (string)systemuser["lastname"];
                    crmIdentity.Email = (string)systemuser["internalemailaddress"];
                    crmIdentity.UserId = resp.UserId;
                    crmIdentity.SetAuthenticated(true);

                    List<string> roles = CrmUtils.GetUserRoles(resp.UserId, service);
                    foreach (string role in roles)
                    {
                        crmIdentity.AddRole(role);
                    }

                    context.User = new GenericPrincipal(crmIdentity, roles.ToArray());
                }
                catch (System.ServiceModel.Security.MessageSecurityException ex)
                {
                    throw new FaultException(ex.Message);
                }
                catch (Exception ex)
                {
                    throw new FaultException(ex.Message);
                }
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Retrieve the working hours of the current user.        
        /// Optionally delete any entity records that were created for this sample.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {

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

                    // Call the method to create any data that this sample requires.
                    CreateRequiredRecords();

                    //<snippetQueryWorkingHoursOfUser1>
                    // Get the current user's information.
                    WhoAmIRequest userRequest = new WhoAmIRequest();
                    WhoAmIResponse userResponse = (WhoAmIResponse)_serviceProxy.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)_serviceProxy.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.");
                    }
                    //</snippetQueryWorkingHoursOfUser1>                    
                }
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Esempio n. 12
0
        public void ProcessWhoAmI()
        {
            WorkAsync(new WorkAsyncInfo
            {
                Message = "Retrieving your user id...",
                Work = (w, e) =>
                {
                    while (e.Cancel == false)
                    {
                        if (w.CancellationPending)
                        {
                            e.Cancel = true;
                        }
                        var request = new WhoAmIRequest();
                        var response = (WhoAmIResponse)Service.Execute(request);

                        e.Result = response.UserId;
                    }
                },
                ProgressChanged = e =>
                {
                    // If progress has to be notified to user, use the following method:
                    //SetWorkingMessage("Message to display");

                    // If progress has to be notified to user, through the
                    // status bar, use the following method
                    if (SendMessageToStatusBar != null)
                        SendMessageToStatusBar(this, new StatusBarMessageEventArgs(50, "progress at 50%"));
                },
                PostWorkCallBack = e =>
                {
                    if (!e.Cancelled)
                    {
                        MessageBox.Show(string.Format("You are {0}", (Guid)e.Result));
                    }
                },
                AsyncArgument = null,
                IsCancelable = true,
                MessageWidth = 340,
                MessageHeight = 150
            });
        }
        /// <summary>
        /// Validate method to attempt to connect to CRM with supplied username/password and then execute a whoami request
        /// </summary>
        /// <param name="username">crm username</param>
        /// <param name="password">crm password</param>
        public override void Validate(string username, string password)
        {
            //get the httpcontext so we can store the user guid for impersonation later
            HttpContext context = HttpContext.Current;

            //if username or password are null, obvs we can't continue
            if (null == username || null == password)
            {
                throw new ArgumentNullException();
            }

            //get the crm connection using the simplified connection string method

            // the following assumes the server url is stored in the web.config appsettings collection like so:
            // <add key="crmconnectionstring" value="Url=https://crm.example.com; "/>
            string connectionString = ConfigurationManager.AppSettings["crmconnectionstring"];
            connectionString += " Username="******"; Password=" + password;

            Microsoft.Xrm.Client.CrmConnection connection = CrmConnection.Parse(connectionString);

            //try the whoami request
            //if it fails (user can't be authenticated, is disabled, etc.), the client will get a soap fault message
            using (OrganizationService service = new OrganizationService(connection))
            {
                try
                {
                    WhoAmIRequest req = new WhoAmIRequest();
                    WhoAmIResponse resp = (WhoAmIResponse)service.Execute(req);
                    List<string> roles = GetUserRoles(resp.UserId, service);
                    context.User = new GenericPrincipal(new GenericIdentity(resp.UserId.ToString()), roles.ToArray());
                }
                catch (System.ServiceModel.Security.MessageSecurityException ex)
                {
                    throw new FaultException(ex.Message);
                }
                catch (Exception ex)
                {
                    throw new FaultException(ex.Message);
                }
            }
        }
Esempio n. 14
0
        public void ProcessWhoAmI()
        {
            WorkAsync(null, (w, e) =>
            {
                var request = new WhoAmIRequest();
                var response = (WhoAmIResponse) Service.Execute(request);

                e.Result = response.UserId;
            },
                e =>
                {
                    MessageBox.Show(string.Format("You are {0}", (Guid) e.Result));
                },
                e =>
                {

                },
                "Retrieving your user id...",
                340,
                150);
        }
Esempio n. 15
0
        public void ProcessWhoAmI()
        {
            WorkAsync(null, (w, e) =>
            {
                var request = new WhoAmIRequest();
                var response = (WhoAmIResponse)Service.Execute(request);

                e.Result = response.UserId;
            },
                e =>
                {
                    MessageBox.Show(string.Format("You are {0}", (Guid)e.Result));
                },
                e =>
                {
                    // If progress has to be notified to user, use the following method:
                    //SetWorkingMessage("Message to display");
                },
                "Retrieving your user id...",
                340,
                150);
        }
Esempio n. 16
0
        /// <summary>
        /// This method creates any entity records that this sample requires.        
        /// </summary>
        public void CreateRequiredRecords()
        {
            // Get the current user's information.
            WhoAmIRequest userRequest = new WhoAmIRequest();
            WhoAmIResponse userResponse = (WhoAmIResponse)_serviceProxy.Execute(userRequest);

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

            _vanId = _serviceProxy.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 = _serviceProxy.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 = _serviceProxy.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 = _serviceProxy.Create(plumberService);

            Console.WriteLine("Created a sample service for the equipment: {0}.", plumberService.Name);
        }
Esempio n. 17
0
        /// <summary>
        /// Creates any entity records that this sample requires.
        /// </summary>
        public void CreateRequiredRecords()
        {
            // For this sample, all required entities are created in the Run() method.
            // Obtain the current user's information.
            WhoAmIRequest who = new WhoAmIRequest();
            WhoAmIResponse whoResp = (WhoAmIResponse)_serviceProxy.Execute(who);
            Guid currentUserId = whoResp.UserId;

            SystemUser currentUser =
                _serviceProxy.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 = SystemUserProvider.GetUserIdIfExist(_serviceProxy,
                _domain, _userName, _firstName, _lastName);

            if(existingUser != null)
                throw new Exception("User already exist!");

            // Set up an Active Directory account in the current domain for this sample.
            String ldapPath = String.Empty;
            Boolean accountSetup = SystemUserProvider.CreateADAccount(_userName, 
                _firstName, _lastName, _serviceProxy, ref ldapPath);
            if (accountSetup)
                Console.WriteLine("An AD account created for '{0}, {1}'", _lastName, _firstName);
            else
                Console.WriteLine("AD account already exist for '{0}, {1}'", _lastName, _firstName);
        }
Esempio n. 18
0
       //</snippetQuickCampaign3>

        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Create a new queue instance.
        /// </summary>
        public void CreateRequiredRecords()
        {
            WhoAmIRequest whoRequest = new WhoAmIRequest();
            _currentUser = ((WhoAmIResponse)_serviceProxy.Execute(whoRequest)).UserId;

            //Create an activity objects which will act like a template during QC distrbution. 
            //The activities created by QC will create activities with content that this activity has
            _templateEmailActivity = new Email()
            {
                Subject = "qcCreatedEmailActivity"
            };

            _templateLetterActivity = new Letter()
            {
                Subject = "qcCreatedLetterActivity"
            };

            // Create accounts on which we want to run QC
            _accountIdArray = new Guid[5];
            for (int i = 0; i < 5; i++)
            {
                Account acct = new Account() {
                    Name = "Account For Quick Campaign " + i.ToString()
                };
                _accountIdArray[i] = _serviceProxy.Create(acct);
                Console.WriteLine("Created {0}.", acct.Name);
            }
        }
        /// <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, OrganizationServiceProxy serviceProxy,
                                              ref String ldapPath)
        {
            String domain;
            Guid   userId = Guid.Empty;

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

            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)serviceProxy.Execute(who);
            Guid           currentUserId = whoResp.UserId;

            SystemUser currentUser =
                serviceProxy.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(serviceProxy, 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(serviceProxy, roleStr);

                    // Associate the user with the role when needed.
                    if (!UserInRole(serviceProxy, 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")
                        };
                        serviceProxy.Execute(associate);
                    }
                }
            }
            else
            {
                // Create the system user in Microsoft Dynamics CRM if the user doesn't
                // already exist.
                userId = CreateSystemUser(userName, firstName, lastName, domain,
                                          roleStr, serviceProxy, ref ldapPath);
            }

            return(userId);
        }
Esempio n. 20
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 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. 21
0
        /// <summary>
        /// This method first checks if the logged on user has prvReadPOAA permissions.
        /// Afterwards,  the method creates the secure custom fields required for this sample,
        /// an account record for testing purposes, and POAA records for the user
        /// and those custom fields.
        /// Finally, the method retrieves the User Shared Attribute permissions for that user.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetRetrieveUserSharedAttributePermissions1>
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    //<snippetRetrieveUserSharedAttributePermissions2>

                    #region Check if this user has prvReadPOAA
                    // Get the GUID of the current user.
                    WhoAmIRequest whoAmI       = new WhoAmIRequest();
                    Guid          userLoggedId =
                        ((WhoAmIResponse)_serviceProxy.Execute(whoAmI)).UserId;
                    Console.WriteLine("User logged: " + userLoggedId);

                    // Check if this user has prvReadPOAA.
                    RetrieveUserPrivilegesRequest userPrivilegesRequest =
                        new RetrieveUserPrivilegesRequest();
                    userPrivilegesRequest.UserId = userLoggedId;
                    RetrieveUserPrivilegesResponse userPrivilegesResponse =
                        (RetrieveUserPrivilegesResponse)_serviceProxy.Execute(userPrivilegesRequest);

                    // Fixed the GUID for prvReadPOAA.
                    Guid prvReadPOAA = new Guid("{68564CD5-2B2E-11DF-80A6-00137299E1C2}");

                    if (userPrivilegesResponse.RolePrivileges.Any(r => r.PrivilegeId.Equals(prvReadPOAA)))
                    {
                        Console.WriteLine("This user DOES have prvReadPOAA");
                    }
                    else
                    {
                        Console.WriteLine("This user DOESN'T have prvReadPOAA");
                    }
                    Console.WriteLine();
                    #endregion Check if this user has prvReadPOAA
                    //</snippetRetrieveUserSharedAttributePermissions2>
                    #region Create an account record

                    // Create an account record
                    Account accountRecord = new Account();
                    accountRecord.Name            = "Ane";
                    accountRecord["secret_phone"] = "123456";
                    _accountRecordId = _serviceProxy.Create(accountRecord);
                    Console.WriteLine("Account record created.");

                    #endregion Create an account record

                    #region Create POAA entity for field #1

                    // Create POAA entity for field #1
                    PrincipalObjectAttributeAccess poaa = new PrincipalObjectAttributeAccess
                    {
                        AttributeId = _secretHomeId,
                        ObjectId    = new EntityReference
                                          (Account.EntityLogicalName, _accountRecordId),
                        PrincipalId = new EntityReference
                                          (SystemUser.EntityLogicalName, userLoggedId),
                        ReadAccess   = true,
                        UpdateAccess = true
                    };

                    _serviceProxy.Create(poaa);
                    Console.WriteLine("POAA record for custom field Secret_Home created.");

                    #endregion Create POAA entity for field #1

                    #region Create POAA entity for field #2

                    // Create POAA entity for field #2
                    poaa = new PrincipalObjectAttributeAccess
                    {
                        AttributeId = _secretPhoneId,
                        ObjectId    = new EntityReference
                                          (Account.EntityLogicalName, _accountRecordId),
                        PrincipalId = new EntityReference
                                          (SystemUser.EntityLogicalName, userLoggedId),
                        ReadAccess   = true,
                        UpdateAccess = true
                    };

                    _serviceProxy.Create(poaa);
                    Console.WriteLine("POAA record for custom field Secret_Phone created.");

                    #endregion Create POAA entity for field #2

                    #region Retrieve User Shared Attribute Permissions
                    // Create the query for retrieve User Shared Attribute permissions.
                    QueryExpression queryPOAA =
                        new QueryExpression("principalobjectattributeaccess");
                    queryPOAA.ColumnSet = new ColumnSet
                                              (new string[] { "attributeid", "readaccess", "updateaccess", "principalid" });
                    queryPOAA.Criteria.FilterOperator = LogicalOperator.And;
                    queryPOAA.Criteria.Conditions.Add
                        (new ConditionExpression("objectid", ConditionOperator.Equal, _accountRecordId));
                    queryPOAA.Criteria.Conditions.Add
                        (new ConditionExpression("principalid", ConditionOperator.EqualUserId));

                    Console.WriteLine();
                    Console.WriteLine("POAA for user: "******"  principalid: " + ((EntityReference)entity["principalid"]).Id);
                            Console.WriteLine("  attributeid: " + entity["attributeid"].ToString());
                            Console.WriteLine("  readaccess: " + entity["readaccess"].ToString());
                            Console.WriteLine("  updateaccess: " + entity["updateaccess"].ToString());
                            Console.WriteLine();
                        }
                    }
                    catch (Exception exc)
                    {
                        Console.WriteLine("Error: " + exc.Message);
                    }

                    #endregion Retrieve User Shared Attribute Permissions

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

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Esempio n. 22
0
        private static void PostToPersonalWalls(CrmServiceClient service)
        {
            Console.WriteLine("\r\n== Working with Personal Walls ==");
            // Create manual (user) posts on a user's Personal wall.
            var whoAmIRequest  = new WhoAmIRequest();
            var whoAmIResponse = (WhoAmIResponse)service.Execute(whoAmIRequest);
            var currentUserRef = new EntityReference(
                SystemUser.EntityLogicalName, whoAmIResponse.UserId);

            // Create a post that mentions lead 1.
            // The Regarding object should be set to the user whose wall the post should
            // be posted to (we'll just use the current user).
            _post1 = new Post
            {
                RegardingObjectId = currentUserRef,
                Source            = new OptionSetValue((int)PostSource.ManualPost),
                Text = String.Format("I'd rather not pursue @[{0},{1},\"{2}\"]",
                                     Lead.EntityTypeCode, _lead1.Id, _lead1.FullName)
            };

            _serviceContext.AddObject(_post1);
            _serviceContext.SaveChanges();
            Console.WriteLine("  Personal wall post 1 was created.");

            // Create a related comment.
            var comment1 = new PostComment
            {
                PostId = _post1.ToEntityReference(),
                Text   = "Personal wall comment 1."
            };

            _serviceContext.AddObject(comment1);
            _serviceContext.SaveChanges();
            Console.WriteLine("  Personal wall comment 1 was created.");

            _post2 = new Post
            {
                RegardingObjectId = currentUserRef,
                Source            = new OptionSetValue((int)PostSource.AutoPost),
                Text = "Personal wall post 2."
            };

            _serviceContext.AddObject(_post2);
            _serviceContext.SaveChanges();
            Console.WriteLine("  Personal wall post 2 was created.");

            // Create a few related comments.
            var comment2 = new PostComment
            {
                PostId = _post2.ToEntityReference(),
                Text   = "Personal wall comment 2."
            };

            var comment3 = new PostComment
            {
                PostId = _post2.ToEntityReference(),
                Text   = "Personal wall comment 3."
            };

            var comment4 = new PostComment
            {
                PostId = _post2.ToEntityReference(),
                Text   = "Personal wall comment 4."
            };

            var comment5 = new PostComment
            {
                PostId = _post2.ToEntityReference(),
                Text   = "Personal wall comment 5."
            };

            _serviceContext.AddObject(comment2);
            _serviceContext.AddObject(comment3);
            _serviceContext.AddObject(comment4);
            _serviceContext.AddObject(comment5);
            _serviceContext.SaveChanges();
            Console.WriteLine("  Personal wall comments 2, 3, 4, and 5 were created.");

            // Create a couple more posts just to show how paging works.
            _post3 = new Post
            {
                RegardingObjectId = currentUserRef,
                Source            = new OptionSetValue((int)PostSource.ManualPost),
                Text = "Personal wall post 3."
            };

            _post4 = new Post
            {
                RegardingObjectId = currentUserRef,
                Source            = new OptionSetValue((int)PostSource.AutoPost),
                Text = "Personal wall post 4."
            };

            _serviceContext.AddObject(_post3);
            _serviceContext.AddObject(_post4);
            _serviceContext.SaveChanges();
            Console.WriteLine("  Personal wall posts 3 and 4 were created.");

            // Retrieve this user's personal wall.
            // Retrieve the first page of posts.
            DisplayPersonalWallPage(service, 1);

            // Retrieve the second page of posts.
            DisplayPersonalWallPage(service, 2);

            // Sleep for a second so that the time of the newly created comment will
            // clearly be later than the previously created posts/comments (otherwise
            // Post 3 will not be escalated to the top of the wall).
            Thread.Sleep(1000);

            // Create a new comment on the last post, which will bring the post to the
            // top.
            var newPostComment = new PostComment
            {
                PostId = _post3.ToEntityReference(),
                Text   = "New comment to show that new comments affect post ordering."
            };

            _serviceContext.AddObject(newPostComment);
            _serviceContext.SaveChanges();
            Console.WriteLine("\r\n  A new comment was created to show effects on post ordering.");

            // Display the first page of the personal wall to showcase the change in
            // ordering.  Post 3 should be at the top.
            DisplayPersonalWallPage(service, 1);

            // Show paging of comments.
            // Retrieve comments 2 at a time, starting with page 1.
            var commentsQuery = new QueryExpression(PostComment.EntityLogicalName)
            {
                ColumnSet = new ColumnSet(true),
                Criteria  = new FilterExpression(LogicalOperator.And),
                PageInfo  = new PagingInfo
                {
                    Count                  = 2,
                    PageNumber             = 1,
                    ReturnTotalRecordCount = true
                }
            };

            commentsQuery.Criteria.AddCondition(
                "postid", ConditionOperator.Equal, _post2.Id);

            // Continue querying for comments until there are no further comments to
            // be retrieved.
            EntityCollection commentsResult;

            do
            {
                commentsResult = service.RetrieveMultiple(commentsQuery);

                // Display the comments that we retrieved.
                Console.WriteLine("\r\n  Comments for lead 2 page {0}",
                                  commentsQuery.PageInfo.PageNumber);
                foreach (PostComment comment in commentsResult.Entities)
                {
                    DisplayComment(comment);
                }

                commentsQuery.PageInfo.PageNumber += 1;
            }while (commentsResult.MoreRecords);
        }
Esempio n. 23
0
        /// <summary>
        /// Imports records to Microsoft Dynamics CRM from the specified .csv file.
        /// </summary>
        public void ImportRecords()
        {
            // Create an import map.
            ImportMap importMap = new ImportMap()
            {
                Name            = "Import Map " + DateTime.Now.Ticks.ToString(),
                Source          = "Import Accounts.csv",
                Description     = "Description of data being imported",
                EntitiesPerFile =
                    new OptionSetValue((int)ImportMapEntitiesPerFile.SingleEntityPerFile),
                EntityState = EntityState.Created
            };
            Guid importMapId = _serviceProxy.Create(importMap);

            // Create column mappings.

            #region Column One Mappings
            // Create a column mapping for a 'text' type field.
            ColumnMapping colMapping1 = new ColumnMapping()
            {
                // Set source properties.
                SourceAttributeName = "src_name",
                SourceEntityName    = "Account_1",

                // Set target properties.
                TargetAttributeName = "name",
                TargetEntityName    = Account.EntityLogicalName,

                // Relate this column mapping with the data map.
                ImportMapId =
                    new EntityReference(ImportMap.EntityLogicalName, importMapId),

                // Force this column to be processed.
                ProcessCode =
                    new OptionSetValue((int)ColumnMappingProcessCode.Process)
            };

            // Create the mapping.
            Guid colMappingId1 = _serviceProxy.Create(colMapping1);
            #endregion

            #region Column Two Mappings
            // Create a column mapping for a 'lookup' type field.
            ColumnMapping colMapping2 = new ColumnMapping()
            {
                // Set source properties.
                SourceAttributeName = "src_parent",
                SourceEntityName    = "Account_1",

                // Set target properties.
                TargetAttributeName = "parentaccountid",
                TargetEntityName    = Account.EntityLogicalName,

                // Relate this column mapping with the data map.
                ImportMapId =
                    new EntityReference(ImportMap.EntityLogicalName, importMapId),

                // Force this column to be processed.
                ProcessCode =
                    new OptionSetValue((int)ColumnMappingProcessCode.Process),
            };

            // Create the mapping.
            Guid colMappingId2 = _serviceProxy.Create(colMapping2);

            // Because we created a column mapping of type lookup, we need to specify lookup details in a lookupmapping.
            // One lookupmapping will be for the parent account, and the other for the current record.
            // This lookupmapping is important because without it the current record
            // cannot be used as the parent of another record.

            // Create a lookup mapping to the parent account.
            LookUpMapping parentLookupMapping = new LookUpMapping()
            {
                // Relate this mapping with its parent column mapping.
                ColumnMappingId =
                    new EntityReference(ColumnMapping.EntityLogicalName, colMappingId2),

                // Force this column to be processed.
                ProcessCode =
                    new OptionSetValue((int)LookUpMappingProcessCode.Process),

                // Set the lookup for an account entity by its name attribute.
                LookUpEntityName    = Account.EntityLogicalName,
                LookUpAttributeName = "name",
                LookUpSourceCode    =
                    new OptionSetValue((int)LookUpMappingLookUpSourceCode.System)
            };

            // Create the lookup mapping.
            Guid parentLookupMappingId = _serviceProxy.Create(parentLookupMapping);

            // Create a lookup on the current record's "src_name" so that this record can
            // be used as the parent account for another record being imported.
            // Without this lookup, no record using this account as its parent will be imported.
            LookUpMapping currentLookUpMapping = new LookUpMapping()
            {
                // Relate this lookup with its parent column mapping.
                ColumnMappingId =
                    new EntityReference(ColumnMapping.EntityLogicalName, colMappingId2),

                // Force this column to be processed.
                ProcessCode =
                    new OptionSetValue((int)LookUpMappingProcessCode.Process),

                // Set the lookup for the current record by its src_name attribute.
                LookUpAttributeName = "src_name",
                LookUpEntityName    = "Account_1",
                LookUpSourceCode    =
                    new OptionSetValue((int)LookUpMappingLookUpSourceCode.Source)
            };

            // Create the lookup mapping
            Guid currentLookupMappingId = _serviceProxy.Create(currentLookUpMapping);
            #endregion

            #region Column Three Mappings
            // Create a column mapping for a 'picklist' type field
            ColumnMapping colMapping3 = new ColumnMapping()
            {
                // Set source properties
                SourceAttributeName = "src_addresstype",
                SourceEntityName    = "Account_1",

                // Set target properties
                TargetAttributeName = "address1_addresstypecode",
                TargetEntityName    = Account.EntityLogicalName,

                // Relate this column mapping with its parent data map
                ImportMapId =
                    new EntityReference(ImportMap.EntityLogicalName, importMapId),

                // Force this column to be processed
                ProcessCode =
                    new OptionSetValue((int)ColumnMappingProcessCode.Process)
            };

            // Create the mapping
            Guid colMappingId3 = _serviceProxy.Create(colMapping3);

            // Because we created a column mapping of type picklist, we need to specify picklist details in a picklistMapping
            PickListMapping pickListMapping1 = new PickListMapping()
            {
                SourceValue = "bill",
                TargetValue = 1,

                // Relate this column mapping with its column mapping data map
                ColumnMappingId =
                    new EntityReference(ColumnMapping.EntityLogicalName, colMappingId3),

                // Force this column to be processed
                ProcessCode =
                    new OptionSetValue((int)PickListMappingProcessCode.Process)
            };

            // Create the mapping
            Guid picklistMappingId1 = _serviceProxy.Create(pickListMapping1);

            // Need a picklist mapping for every address type code expected
            PickListMapping pickListMapping2 = new PickListMapping()
            {
                SourceValue = "ship",
                TargetValue = 2,

                // Relate this column mapping with its column mapping data map
                ColumnMappingId =
                    new EntityReference(ColumnMapping.EntityLogicalName, colMappingId3),

                // Force this column to be processed
                ProcessCode =
                    new OptionSetValue((int)PickListMappingProcessCode.Process)
            };

            // Create the mapping
            Guid picklistMappingId2 = _serviceProxy.Create(pickListMapping2);
            #endregion

            // Create Import
            Import import = new Import()
            {
                // IsImport is obsolete; use ModeCode to declare Create or Update.
                ModeCode = new OptionSetValue((int)ImportModeCode.Create),
                Name     = "Importing data"
            };
            Guid importId = _serviceProxy.Create(import);

            // Create Import File.
            ImportFile importFile = new ImportFile()
            {
                Content                  = BulkImportHelper.ReadCsvFile("Import Accounts.csv"), // Read contents from disk.
                Name                     = "Account record import",
                IsFirstRowHeader         = true,
                ImportMapId              = new EntityReference(ImportMap.EntityLogicalName, importMapId),
                UseSystemMap             = false,
                Source                   = "Import Accounts.csv",
                SourceEntityName         = "Account_1",
                TargetEntityName         = Account.EntityLogicalName,
                ImportId                 = new EntityReference(Import.EntityLogicalName, importId),
                EnableDuplicateDetection = false,
                FieldDelimiterCode       =
                    new OptionSetValue((int)ImportFileFieldDelimiterCode.Comma),
                DataDelimiterCode =
                    new OptionSetValue((int)ImportFileDataDelimiterCode.DoubleQuote),
                ProcessCode =
                    new OptionSetValue((int)ImportFileProcessCode.Process)
            };

            // Get the current user to set as record owner.
            WhoAmIRequest  systemUserRequest  = new WhoAmIRequest();
            WhoAmIResponse systemUserResponse =
                (WhoAmIResponse)_serviceProxy.Execute(systemUserRequest);

            // Set the owner ID.
            importFile.RecordsOwnerId =
                new EntityReference(SystemUser.EntityLogicalName, systemUserResponse.UserId);

            Guid importFileId = _serviceProxy.Create(importFile);

            //<snippetImportWithCreate1>
            // Retrieve the header columns used in the import file.
            GetHeaderColumnsImportFileRequest headerColumnsRequest = new GetHeaderColumnsImportFileRequest()
            {
                ImportFileId = importFileId
            };
            GetHeaderColumnsImportFileResponse headerColumnsResponse =
                (GetHeaderColumnsImportFileResponse)_serviceProxy.Execute(headerColumnsRequest);

            // Output the header columns.
            int columnNum = 1;
            foreach (string headerName in headerColumnsResponse.Columns)
            {
                Console.WriteLine("Column[" + columnNum.ToString() + "] = " + headerName);
                columnNum++;
            }
            //</snippetImportWithCreate1>

            //<snippetImportWithCreate2>
            // Parse the import file.
            ParseImportRequest parseImportRequest = new ParseImportRequest()
            {
                ImportId = importId
            };
            ParseImportResponse parseImportResponse =
                (ParseImportResponse)_serviceProxy.Execute(parseImportRequest);
            Console.WriteLine("Waiting for Parse async job to complete");
            //</snippetImportWithCreate2>
            BulkImportHelper.WaitForAsyncJobCompletion(_serviceProxy, parseImportResponse.AsyncOperationId);
            BulkImportHelper.ReportErrors(_serviceProxy, importFileId);

            //<snippetImportWithCreate3>
            // Retrieve the first two distinct values for column 1 from the parse table.
            // NOTE: You must create the parse table first using the ParseImport message.
            // The parse table is not accessible after ImportRecordsImportResponse is called.
            GetDistinctValuesImportFileRequest distinctValuesRequest = new GetDistinctValuesImportFileRequest()
            {
                columnNumber   = 1,
                ImportFileId   = importFileId,
                pageNumber     = 1,
                recordsPerPage = 2,
            };
            GetDistinctValuesImportFileResponse distinctValuesResponse =
                (GetDistinctValuesImportFileResponse)_serviceProxy.Execute(distinctValuesRequest);

            // Output the distinct values.  In this case: (column 1, row 1) and (column 1, row 2).
            int cellNum = 1;
            foreach (string cellValue in distinctValuesResponse.Values)
            {
                Console.WriteLine("(1, " + cellNum.ToString() + "): " + cellValue);
                Console.WriteLine(cellValue);
                cellNum++;
            }
            //</snippetImportWithCreate3>

            //<snippetImportWithCreate4>
            // Retrieve data from the parse table.
            // NOTE: You must create the parse table first using the ParseImport message.
            // The parse table is not accessible after ImportRecordsImportResponse is called.
            RetrieveParsedDataImportFileRequest parsedDataRequest = new RetrieveParsedDataImportFileRequest()
            {
                ImportFileId = importFileId,
                PagingInfo   = new PagingInfo()
                {
                    // Specify the number of entity instances returned per page.
                    Count = 2,
                    // Specify the number of pages returned from the query.
                    PageNumber = 1,
                    // Specify a total number of entity instances returned.
                    PagingCookie = "1"
                }
            };

            RetrieveParsedDataImportFileResponse parsedDataResponse =
                (RetrieveParsedDataImportFileResponse)_serviceProxy.Execute(parsedDataRequest);

            // Output the first two rows retrieved.
            int rowCount = 1;
            foreach (string[] rows in parsedDataResponse.Values)
            {
                int colCount = 1;
                foreach (string column in rows)
                {
                    Console.WriteLine("(" + rowCount.ToString() + "," + colCount.ToString() + ") = " + column);
                    colCount++;
                }
                rowCount++;
            }
            //</snippetImportWithCreate4>

            //<snippetImportWithCreate5>
            // Transform the import
            TransformImportRequest transformImportRequest = new TransformImportRequest()
            {
                ImportId = importId
            };
            TransformImportResponse transformImportResponse =
                (TransformImportResponse)_serviceProxy.Execute(transformImportRequest);
            Console.WriteLine("Waiting for Transform async job to complete");
            //</snippetImportWithCreate5>
            BulkImportHelper.WaitForAsyncJobCompletion(_serviceProxy, transformImportResponse.AsyncOperationId);
            BulkImportHelper.ReportErrors(_serviceProxy, importFileId);

            //<snippetImportWithCreate6>
            // Upload the records.
            ImportRecordsImportRequest importRequest = new ImportRecordsImportRequest()
            {
                ImportId = importId
            };
            ImportRecordsImportResponse importResponse =
                (ImportRecordsImportResponse)_serviceProxy.Execute(importRequest);
            Console.WriteLine("Waiting for ImportRecords async job to complete");
            //</snippetImportWithCreate6>
            BulkImportHelper.WaitForAsyncJobCompletion(_serviceProxy, importResponse.AsyncOperationId);
            BulkImportHelper.ReportErrors(_serviceProxy, importFileId);
        }
Esempio n. 24
0
        /// <summary>
        /// This sample shows how to send a bulk email and monitor its progress.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user is prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy is properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    #region Create and send SendBulkEmail

                    Console.WriteLine();
                    Console.WriteLine("Creating and sending SendBulkEmail.");

                    // Get a system user to use as the sender.
                    WhoAmIRequest  emailSenderRequest  = new WhoAmIRequest();
                    WhoAmIResponse emailSenderResponse =
                        _serviceProxy.Execute(emailSenderRequest) as WhoAmIResponse;

                    // Set trackingId for bulk mail request.
                    Guid trackingId = Guid.NewGuid();

                    SendBulkMailRequest bulkMailRequest = new SendBulkMailRequest()
                    {
                        // Create a query expression for the bulk operation to use to retrieve
                        // the contacts in the email list.
                        Query = new QueryExpression()
                        {
                            EntityName = Contact.EntityLogicalName,
                            ColumnSet  = new ColumnSet(new String[] { "contactid" }),
                            Criteria   = new FilterExpression()
                            {
                                Conditions =
                                {
                                    new ConditionExpression("contactid", ConditionOperator.In, _contactsIds)
                                }
                            }
                        },
                        // Set the Sender.
                        Sender = new EntityReference(SystemUser.EntityLogicalName, emailSenderResponse.UserId),
                        // Set the RegardingId - this field is required.
                        RegardingId   = Guid.Empty,
                        RegardingType = SystemUser.EntityLogicalName,
                        // Use a built-in Microsoft Dynamics CRM email template.
                        // NOTE: The email template's "template type" must match the type of
                        // customers in the email list.  Our list contains contacts, so our
                        // template must be for contacts.
                        TemplateId = new Guid("07B94C1D-C85F-492F-B120-F0A743C540E6"),
                        RequestId  = trackingId
                    };

                    // Execute the async bulk email request
                    SendBulkMailResponse resp = (SendBulkMailResponse)
                                                _serviceProxy.Execute(bulkMailRequest);

                    Console.WriteLine("  Sent Bulk Email.");
                    #endregion

                    #region Monitoring SendBulkEmail

                    Console.WriteLine();
                    Console.WriteLine("Starting monitoring process..");

                    // Now that we've executed the bulk operation, we need to retrieve it
                    // using our tracking Id.

                    QueryByAttribute bulkQuery = new QueryByAttribute()
                    {
                        EntityName = AsyncOperation.EntityLogicalName,
                        ColumnSet  = new ColumnSet(new string[] { "requestid", "statecode" }),
                        Attributes = { "requestid" },
                        Values     = { trackingId }
                    };

                    // Retrieve the bulk email async operation.
                    EntityCollection aResponse = _serviceProxy.RetrieveMultiple(bulkQuery);

                    Console.WriteLine("  Retrieved Bulk Email Async Operation.");

                    // Monitor the async operation via polling.
                    int secondsTicker = ARBITRARY_MAX_POLLING_TIME;

                    AsyncOperation createdBulkMailOperation = null;

                    Console.WriteLine("  Checking operation's state for " + ARBITRARY_MAX_POLLING_TIME + " seconds.");
                    Console.WriteLine();

                    while (secondsTicker > 0)
                    {
                        // Make sure the async operation was retrieved.
                        if (aResponse.Entities.Count > 0)
                        {
                            // Grab the one bulk operation that has been created.
                            createdBulkMailOperation = (AsyncOperation)aResponse.Entities[0];

                            // Check the operation's state.
                            if (createdBulkMailOperation.StateCode.Value !=
                                AsyncOperationState.Completed)
                            {
                                // The operation has not yet completed.
                                // Wait a second for the status to change.
                                System.Threading.Thread.Sleep(1000);
                                secondsTicker--;

                                // Retrieve a fresh version the bulk delete operation.
                                aResponse = _serviceProxy.RetrieveMultiple(bulkQuery);
                            }
                            else
                            {
                                // Stop polling because the operation's state is now complete.
                                secondsTicker = 0;
                            }
                        }
                        else
                        {
                            // Wait a second for the async operation to activate.
                            System.Threading.Thread.Sleep(1000);
                            secondsTicker--;

                            // Retrieve the entity again
                            aResponse = _serviceProxy.RetrieveMultiple(bulkQuery);
                        }
                    }

                    // When the bulk email operation has completed, all sent emails will
                    // have a status of "Pending Send" and will be picked up by your email
                    // router.  Alternatively, you can then use BackgroundSendEmail to download
                    // all the emails created with the SendBulkEmail message.
                    // See the BackgroundSendEmail sample for an example.
                    #endregion

                    #region Check success

                    // Validate async operation succeeded
                    if (createdBulkMailOperation.StateCode.Value == AsyncOperationState.Completed)
                    {
                        Console.WriteLine("Operation Completed.");
                    }
                    else
                    {
                        Console.WriteLine("Operation not completed yet.");
                    }

                    #endregion

                    DeleteRequiredRecords(promptforDelete);
                }
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Esempio n. 25
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 sales people that will be added to the team.
                    salesPersons = SystemUserProvider.RetrieveSalespersons(service, ref ldapPath);

                    // Get the ID's of the current user and business unit.
                    var who         = new WhoAmIRequest();
                    var whoResponse = (WhoAmIResponse)service.Execute(who);
                    _currentUserId = whoResponse.UserId;
                    businessUnitId = whoResponse.BusinessUnitId;

                    // Create a access team.
                    var team = new Team
                    {
                        AdministratorId = new EntityReference(
                            "systemuser", _currentUserId),
                        Name           = "UserAccess Test Team",
                        BusinessUnitId = new EntityReference(
                            "businessunit", businessUnitId),
                        TeamType = new OptionSetValue((int)TeamTeamType.Access),
                    };

                    _teamId = service.Create(team);
                    Console.WriteLine("Created an access team named '{0}'.", team.Name);

                    // Add two sales people to the access team.
                    var addToTeamRequest = new AddMembersTeamRequest
                    {
                        TeamId    = _teamId,
                        MemberIds = new[] { salesPersons[0], salesPersons[1] }
                    };
                    service.Execute(addToTeamRequest);
                    Console.WriteLine("Added two sales people to the team.");

                    // Grant the team read/write access to an account.
                    var accountReference   = new EntityReference(Account.EntityLogicalName, _accountId);
                    var teamReference      = new EntityReference(Team.EntityLogicalName, _teamId);
                    var grantAccessRequest = new GrantAccessRequest
                    {
                        PrincipalAccess = new PrincipalAccess
                        {
                            AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess,
                            Principal  = teamReference
                        },
                        Target = accountReference
                    };
                    service.Execute(grantAccessRequest);
                    Console.WriteLine("Granted read/write access on the account record to the team.");

                    // Retrieve and display access information for the account.
                    RetrieveAndDisplayEntityAccess(service, accountReference);

                    // Display the account access for the team and its members.
                    var currentUserReference = new EntityReference(
                        SystemUser.EntityLogicalName, _currentUserId);
                    RetrieveAndDisplayPrincipalAccess(service, accountReference, currentUserReference,
                                                      "Current User");
                    var firstSalesPersonReference = new EntityReference(
                        SystemUser.EntityLogicalName, salesPersons[0]);
                    RetrieveAndDisplayPrincipalAccess(service, accountReference, firstSalesPersonReference,
                                                      "Sales Person");
                    var secondSalesPersonReference = new EntityReference(
                        SystemUser.EntityLogicalName, salesPersons[1]);
                    RetrieveAndDisplayPrincipalAccess(service, accountReference, secondSalesPersonReference,
                                                      "Sales Person");

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

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

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

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Esempio n. 26
0
        /// <summary>
        /// Perform the main action of the sample - issuing a BulkDeleteRequest.
        /// </summary>
        /// <param name="useRecurrence">
        /// whether or not to create a recurring BulkDeleteRequest.
        /// </param>
        private void PerformBulkDelete(bool useRecurrence, bool promptToDelete)
        {
            try
            {
                Console.WriteLine("Performing Bulk Delete Operation");

                // Query for a system user to send an email to after the bulk delete
                // operation completes.
                var  userRequest   = new WhoAmIRequest();
                var  userResponse  = (WhoAmIResponse)_serviceProxy.Execute(userRequest);
                Guid currentUserId = userResponse.UserId;

                Console.WriteLine("  Requesting user retrieved.");

                // Create a condition for a bulk delete request.
                // NOTE: If no records are found that match this condition, the bulk delete
                // will not fail.  It will succeed with 0 successes and 0 failures.
                var deleteCondition = new ConditionExpression(
                    "name", ConditionOperator.Equal, "Fourth Coffee");

                // Create a fiter expression for the bulk delete request.
                var deleteFilter = new FilterExpression();
                deleteFilter.Conditions.Add(deleteCondition);

                // Create the bulk delete query set.
                var bulkDeleteQuery = new QueryExpression
                {
                    EntityName = Account.EntityLogicalName,
                    Distinct   = false,
                    Criteria   = deleteFilter
                };

                // Create the bulk delete request.
                var bulkDeleteRequest = new BulkDeleteRequest
                {
                    JobName               = "Sample Bulk Delete",
                    QuerySet              = new[] { bulkDeleteQuery },
                    StartDateTime         = DateTime.Now,
                    ToRecipients          = new[] { currentUserId },
                    CCRecipients          = new Guid[] {},
                    SendEmailNotification = true,
                    RecurrencePattern     = String.Empty
                };

                // Create a recurring BulkDeleteOperation.
                if (useRecurrence)
                {
                    bulkDeleteRequest.RecurrencePattern = "FREQ=DAILY;INTERVAL=1;";
                }

                // Submit the bulk delete job.
                // NOTE: Because this is an asynchronous operation, the response will be
                // immediate.
                var bulkDeleteResponse =
                    (BulkDeleteResponse)_serviceProxy.Execute(bulkDeleteRequest);
                _asyncOperationId = bulkDeleteResponse.JobId;

                Console.WriteLine("  The Bulk Delete Request was made and the Bulk\n" +
                                  "    Delete Operation should be created.");

                // To monitor the asynchronous operation, retrieve the
                // bulkdeleteoperation object.
                // NOTE: There will be a period of time from when the async operation
                // request was submitted to the time when a successful query for that
                // async operation can be made.  When using plug-ins, events can be
                // subscribed to that will fire when the async operation status changes.
                var bulkQuery = new QueryByAttribute();
                bulkQuery.ColumnSet  = new ColumnSet(true);
                bulkQuery.EntityName = BulkDeleteOperation.EntityLogicalName;

                // NOTE: When the bulk delete operation was submitted, the GUID that was
                // returned was the asyncoperationid, not the bulkdeleteoperationid.
                bulkQuery.Attributes.Add("asyncoperationid");
                bulkQuery.Values.Add(bulkDeleteResponse.JobId);

                // With only the asyncoperationid at this point, a RetrieveMultiple is
                // required to get the bulk delete operation created above.
                var entityCollection =
                    _serviceProxy.RetrieveMultiple(bulkQuery);
                BulkDeleteOperation createdBulkDeleteOperation = null;

                // When creating a recurring BulkDeleteOperation, the BulkDeleteOperation
                // will be in suspended status after the current instance has completed.
                // When creating a non-recurring BulkDeleteOperation, it will be in
                // Completed status when it is finished.
                var bulkOperationEnded = useRecurrence
                    ? BulkDeleteOperationState.Suspended
                    : BulkDeleteOperationState.Completed;

                createdBulkDeleteOperation = RetrieveBulkDeleteOperation(
                    bulkQuery, entityCollection, bulkOperationEnded);
                _bulkDeleteOperationId = createdBulkDeleteOperation.Id;

                if (createdBulkDeleteOperation != null)
                {
                    // If the BulkDeleteOperation is recurring, the status will be
                    // "Waiting" after the operation completes this instance.  If it is
                    // non-recurring, the status will be "Succeeded".
                    var bulkOperationSuccess = useRecurrence
                        ? bulkdeleteoperation_statuscode.Waiting
                        : bulkdeleteoperation_statuscode.Succeeded;

                    InspectBulkDeleteOperation(createdBulkDeleteOperation,
                                               bulkOperationEnded, bulkOperationSuccess, useRecurrence);

                    DeleteRecords(promptToDelete);
                }
                else
                {
                    Console.WriteLine("  The Bulk Delete Operation could not be retrieved.");
                }
            }
            catch (System.Web.Services.Protocols.SoapException)
            {
                // Perform error handling here.
                throw;
            }
        }
Esempio n. 27
0
        /// <summary>
        /// Performs the main operation of the sample - performs a bulk delete on inactive
        /// opportunities and activities to remove them from the system.
        /// </summary>
        private void PerformBulkDeleteBackup()
        {
            try
            {
                // Query for a system user to send an email to after the bulk delete
                // operation completes.
                var  userRequest   = new WhoAmIRequest();
                var  userResponse  = (WhoAmIResponse)_serviceProxy.Execute(userRequest);
                Guid currentUserId = userResponse.UserId;

                //<snippetBulkDelete>
                // Create a condition for a bulk delete request.
                // NOTE: This sample uses very specific queries for deleting records
                // that have been manually exported in order to free space.
                QueryExpression opportunitiesQuery = BuildOpportunityQuery();

                // Create the bulk delete request.
                BulkDeleteRequest bulkDeleteRequest = new BulkDeleteRequest();

                // Set the request properties.
                bulkDeleteRequest.JobName = "Backup Bulk Delete";

                // Querying activities
                bulkDeleteRequest.QuerySet = new QueryExpression[]
                {
                    opportunitiesQuery,
                    BuildActivityQuery(Task.EntityLogicalName),
                    BuildActivityQuery(Fax.EntityLogicalName),
                    BuildActivityQuery(PhoneCall.EntityLogicalName),
                    BuildActivityQuery(Email.EntityLogicalName),
                    BuildActivityQuery(Letter.EntityLogicalName),
                    BuildActivityQuery(Appointment.EntityLogicalName),
                    BuildActivityQuery(ServiceAppointment.EntityLogicalName),
                    BuildActivityQuery(CampaignResponse.EntityLogicalName),
                    BuildActivityQuery(RecurringAppointmentMaster.EntityLogicalName)
                };

                // Set the start time for the bulk delete.
                bulkDeleteRequest.StartDateTime = DateTime.Now;

                // Set the required recurrence pattern.
                bulkDeleteRequest.RecurrencePattern = String.Empty;

                // Set email activity properties.
                bulkDeleteRequest.SendEmailNotification = false;
                bulkDeleteRequest.ToRecipients          = new Guid[] { currentUserId };
                bulkDeleteRequest.CCRecipients          = new Guid[] { };

                // Submit the bulk delete job.
                // NOTE: Because this is an asynchronous operation, the response will be immediate.
                _bulkDeleteResponse =
                    (BulkDeleteResponse)_serviceProxy.Execute(bulkDeleteRequest);
                Console.WriteLine("The bulk delete operation has been requested.");
                //</snippetBulkDelete>

                CheckSuccess();
            }
            catch (System.Web.Services.Protocols.SoapException)
            {
                // Perform error handling here.
                throw;
            }
            catch (Exception)
            {
                throw;
            }
        }
Esempio n. 28
0
        /// <summary>
        /// Create an e-mail activity instance from the specified e-mail message.
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        /// </summary>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // Create a contact to send an email to (To: field)
                    Contact emailContact = new Contact()
                    {
                        FirstName     = "Lisa",
                        LastName      = "Andrews",
                        EMailAddress1 = "*****@*****.**"
                    };
                    _contactId = _serviceProxy.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)_serviceProxy.Execute(systemUserRequest);

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

                    //<snippetDeliverPromoteEmail1>

                    // 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)_serviceProxy.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)_serviceProxy.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.");
                    }

                    //</snippetDeliverPromoteEmail1>

                    DeleteRequiredRecords(promptForDelete);
                }
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Esempio n. 29
0
        private void DistributeCampaign()
        {
            Console.WriteLine("=== Creating and Distributing the Campaign ===");
            // Create the campaign.
            var campaign = new Campaign
            {
                Name = "Sample Campaign"
            };

            _originalCampaignId = _serviceProxy.Create(campaign);

            NotifyEntityCreated(Campaign.EntityLogicalName, _originalCampaignId);

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

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

            _campaignId = copyCampaignResponse.CampaignCopyId;

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

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

            _campaignActivityId = _serviceProxy.Create(activity);

            NotifyEntityCreated(CampaignActivity.EntityLogicalName, _campaignActivityId);

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

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

            _serviceProxy.Execute(addListToCampaignRequest);

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

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

            _serviceProxy.Execute(addListToActivityRequest);

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

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

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

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

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

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

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

            Console.WriteLine("  Contacts with the following GUIDs were distributed to:");
            foreach (var member in retrieveMembersResponse.EntityCollection.Entities)
            {
                Console.WriteLine("\t{{{0}}}", member.Id);
            }
        }
Esempio n. 30
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 void CreateRequiredRecords()
        {
            // 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 = _serviceProxy.Create(newQueue);

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

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

            _letterId = _serviceProxy.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 = _serviceProxy.Create(item);

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

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

            ColumnSet  columnSet   = new ColumnSet("fullname");
            SystemUser currentUser = (SystemUser)_serviceProxy.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)
            };

            _serviceProxy.Update(queueItem);

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

            return;
        }
Esempio n. 31
0
        public static object[] GetCurrentUser(IOrganizationService _Service, DataTable _TimeEntryCache, Boolean FromCache, ConnectionDetail cnnDetail)
        {
            // A24 JNE 24.9.2015
            if (_Service == null && FromCache == false)
            {
                return(null);
            }

            Guid   userGuid = Guid.Empty;
            string fullname = "";

            String _User = String.Empty;

            if (cnnDetail.IsCustomAuth)
            {
                if (cnnDetail.UserName != String.Empty)
                {
                    _User = String.Format("{0}\\{1}", cnnDetail.UserDomain, cnnDetail.UserName);
                }
                else
                {
                    _User = cnnDetail.UserName;
                }
            }
            else
            {
                _User = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
            }



            try
            {
                if (!FromCache)
                {
                    WhoAmIRequest  userRequest = new WhoAmIRequest();
                    WhoAmIResponse user        = (WhoAmIResponse)_Service.Execute(userRequest);
                    userGuid = user.UserId;

                    Entity _user = _Service.Retrieve(SystemUser.EntityLogicalName, userGuid, new ColumnSet(true));

                    if (_user.Contains("fullname"))
                    {
                        fullname = _user.Attributes["fullname"].ToString();
                    }
                }
            }
            catch { }

            DataRow _dr       = null;
            String  _tmp_User = _User;

            _tmp_User = _tmp_User.Replace("\\", "_");
            _tmp_User = _tmp_User.Replace(".", "_");

            if (userGuid != Guid.Empty)
            {
                // Update Cache
                if ((_dr = GetCacheItemBySubType(_TimeEntryCache, "SETTING_" + _tmp_User, "CURRENT_MSCRM_USER")) == null)
                {
                    // Create New
                    _dr                  = _TimeEntryCache.NewRow();
                    _dr["id"]            = Guid.NewGuid().ToString();
                    _dr["type"]          = "SETTING_" + _tmp_User;
                    _dr["subtype"]       = "CURRENT_MSCRM_USER";
                    _dr["mscrmid"]       = "";
                    _dr["mscrmparentid"] = "";
                    _dr["description"]   = "";
                    _dr["zusatzinfo1"]   = fullname;
                    _dr["zusatzinfo2"]   = userGuid.ToString();

                    _TimeEntryCache.Rows.Add(_dr);
                    _TimeEntryCache.AcceptChanges();
                }
                else
                {
                    // Update
                    _dr["zusatzinfo1"] = fullname;
                    _dr["zusatzinfo2"] = userGuid.ToString();
                    _TimeEntryCache.AcceptChanges();
                }
            }
            else
            {
                // Try get User from Cache
                if ((_dr = GetCacheItemBySubType(_TimeEntryCache, "SETTING_" + _tmp_User, "CURRENT_MSCRM_USER")) != null)
                {
                    userGuid = new Guid(_dr["zusatzinfo2"].ToString());
                    fullname = _dr["zusatzinfo1"].ToString();
                }
            }

            try
            {
                object[] or = new object[] { userGuid, fullname };
                return(or);
            }
            catch (Exception ex)
            {
            }

            return(null);
        }
        private void WhoAmI()
        {
            int i = 0;

            do
            {
                WhoAmIRequest request = new WhoAmIRequest();
                WhoAmIResponse response = (WhoAmIResponse)this.service.Execute(request);

                i++;

                ccsb.SetMessage("Doing...");
                ccsb.SetProgress(i * 10);

                MessageBox.Show(this, "Your ID is: " + response.UserId.ToString("B"));
            } while (i < 1);

            ccsb.SetMessage("Done");
            ccsb.SetProgress(null);
        }
Esempio n. 33
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, OrganizationServiceProxy serviceProxy,
            ref String ldapPath)
        {
            String domain;
            Guid userId = Guid.Empty;

            if (serviceProxy == null)
                throw new ArgumentNullException("serviceProxy");

            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)serviceProxy.Execute(who);
            Guid currentUserId = whoResp.UserId;

            SystemUser currentUser =
                serviceProxy.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(serviceProxy, 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(serviceProxy, roleStr);

                    // Associate the user with the role when needed.
                    if (!UserInRole(serviceProxy, 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")
                        };
                        serviceProxy.Execute(associate);
                    }
                }
            }
            else
            {
                // Create the system user in Microsoft Dynamics CRM if the user doesn't 
                // already exist.
                userId = CreateSystemUser(userName, firstName, lastName, domain,
                    roleStr, serviceProxy, ref ldapPath);
            }

            return userId;
        }
        /// <summary>
        /// This method first checks if the logged on user has prvReadPOAA permissions. 
        /// Afterwards,  the method creates the secure custom fields required for this sample,
        /// an account record for testing purposes, and POAA records for the user
        /// and those custom fields.
        /// Finally, the method retrieves the User Shared Attribute permissions for that user.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetRetrieveUserSharedAttributePermissions1>
                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    //<snippetRetrieveUserSharedAttributePermissions2>

                    #region Check if this user has prvReadPOAA
                    // Get the GUID of the current user.
                    WhoAmIRequest whoAmI = new WhoAmIRequest();
                    Guid userLoggedId = 
                        ((WhoAmIResponse)_serviceProxy.Execute(whoAmI)).UserId;
                    Console.WriteLine("User logged: " + userLoggedId);

                    // Check if this user has prvReadPOAA.
                    RetrieveUserPrivilegesRequest userPrivilegesRequest = 
                        new RetrieveUserPrivilegesRequest();
                    userPrivilegesRequest.UserId = userLoggedId;
                    RetrieveUserPrivilegesResponse userPrivilegesResponse =
                        (RetrieveUserPrivilegesResponse)_serviceProxy.Execute(userPrivilegesRequest);

                    // Fixed the GUID for prvReadPOAA.
                    Guid prvReadPOAA = new Guid("{68564CD5-2B2E-11DF-80A6-00137299E1C2}");

                    if (userPrivilegesResponse.RolePrivileges.Any(r => r.PrivilegeId.Equals(prvReadPOAA)))
                    {
                        Console.WriteLine("This user DOES have prvReadPOAA");
                    }
                    else
                    {
                        Console.WriteLine("This user DOESN'T have prvReadPOAA");
                    }
                    Console.WriteLine();
                    #endregion Check if this user has prvReadPOAA
                    //</snippetRetrieveUserSharedAttributePermissions2>
                    #region Create an account record

                    // Create an account record
                    Account accountRecord = new Account();
                    accountRecord.Name = "Ane";
                    accountRecord["secret_phone"] = "123456";
                    _accountRecordId = _serviceProxy.Create(accountRecord);
                    Console.WriteLine("Account record created.");

                    #endregion Create an account record

                    #region Create POAA entity for field #1

                    // Create POAA entity for field #1
                    PrincipalObjectAttributeAccess poaa = new PrincipalObjectAttributeAccess
                    {
                        AttributeId = _secretHomeId,
                        ObjectId = new EntityReference
                            (Account.EntityLogicalName, _accountRecordId),
                        PrincipalId = new EntityReference
                            (SystemUser.EntityLogicalName, userLoggedId),
                        ReadAccess = true,
                        UpdateAccess = true
                    };

                    _serviceProxy.Create(poaa);
                    Console.WriteLine("POAA record for custom field Secret_Home created.");

                    #endregion Create POAA entity for field #1

                    #region Create POAA entity for field #2

                    // Create POAA entity for field #2
                    poaa = new PrincipalObjectAttributeAccess
                    {
                        AttributeId = _secretPhoneId,
                        ObjectId = new EntityReference
                            (Account.EntityLogicalName, _accountRecordId), 
                        PrincipalId = new EntityReference
                            (SystemUser.EntityLogicalName, userLoggedId),
                        ReadAccess = true,
                        UpdateAccess = true
                    };

                    _serviceProxy.Create(poaa);
                    Console.WriteLine("POAA record for custom field Secret_Phone created.");

                    #endregion Create POAA entity for field #2

                    #region Retrieve User Shared Attribute Permissions
                    // Create the query for retrieve User Shared Attribute permissions.
                    QueryExpression queryPOAA =
                        new QueryExpression("principalobjectattributeaccess");
                    queryPOAA.ColumnSet = new ColumnSet
                        (new string[] { "attributeid", "readaccess", "updateaccess", "principalid" });
                    queryPOAA.Criteria.FilterOperator = LogicalOperator.And;
                    queryPOAA.Criteria.Conditions.Add
                        (new ConditionExpression("objectid", ConditionOperator.Equal, _accountRecordId));
                    queryPOAA.Criteria.Conditions.Add
                        (new ConditionExpression("principalid", ConditionOperator.EqualUserId));

                    Console.WriteLine();
                    Console.WriteLine("POAA for user: "******"  principalid: " + ((EntityReference)entity["principalid"]).Id);
                            Console.WriteLine("  attributeid: " + entity["attributeid"].ToString());
                            Console.WriteLine("  readaccess: " + entity["readaccess"].ToString());
                            Console.WriteLine("  updateaccess: " + entity["updateaccess"].ToString());
                            Console.WriteLine();
                        }
                    }
                    catch (Exception exc)
                    {
                        Console.WriteLine("Error: " + exc.Message);
                    }

                    #endregion Retrieve User Shared Attribute Permissions

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

            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Esempio n. 35
0
        /// <summary>
        /// This method first connects to the Outlook service. Afterwards,
        /// client information is retrieved and the client state is changed.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {

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

                    //<snippetRetrieveDataFilters1>

                    // Create and Retrieve Offline Filter
                    // In your Outlook client, this will appear in the System Filters tab
                    // under File | CRM | Synchronize | Outlook Filters.
                    Console.Write("Creating offline filter");
                    String contactName = String.Format("offlineFilteredContact {0}",
                        DateTime.Now.ToLongTimeString());
                    String fetchXml = String.Format("<fetch version=\"1.0\" output-format=\"xml-platform\" mapping=\"logical\"><entity name=\"contact\"><attribute name=\"contactid\" /><filter type=\"and\">" +
                        "<condition attribute=\"ownerid\" operator=\"eq-userid\" /><condition attribute=\"description\" operator=\"eq\" value=\"{0}\" />" +
                        "<condition attribute=\"statecode\" operator=\"eq\" value=\"0\" /></filter></entity></fetch>", contactName);
                    SavedQuery filter = new SavedQuery();
                    filter.FetchXml = fetchXml;
                    filter.IsQuickFindQuery = false;
                    filter.QueryType = SavedQueryQueryType.OfflineFilters;
                    filter.ReturnedTypeCode = Contact.EntityLogicalName;
                    filter.Name = "ReadOnlyFilter_" + contactName;
                    filter.Description = "Sample offline filter for Contact entity";
                    _offlineFilter = _serviceProxy.Create(filter);

                    Console.WriteLine(" and retrieving offline filter");
                    SavedQuery result = (SavedQuery)_serviceProxy.Retrieve(
                        SavedQuery.EntityLogicalName,
                        _offlineFilter,
                        new ColumnSet("name", "description"));
                    Console.WriteLine("Name: {0}", result.Name);
                    Console.WriteLine("Description: {0}", result.Description);
                    Console.WriteLine();

                    // Create and Retrieve Offline Template
                    // In your Outlook client, this will appear in the User Filters tab
                    // under File | CRM | Synchronize | Outlook Filters.
                    Console.Write("Creating offline template");
                    String accountName = String.Format("offlineFilteredAccount {0}",
                        DateTime.Now.ToLongTimeString());
                    fetchXml = String.Format("<fetch version=\"1.0\" output-format=\"xml-platform\" mapping=\"logical\"><entity name=\"account\"><attribute name=\"accountid\" /><filter type=\"and\">" +
                        "<condition attribute=\"ownerid\" operator=\"eq-userid\" /><condition attribute=\"name\" operator=\"eq\" value=\"{0}\" />" +
                        "<condition attribute=\"statecode\" operator=\"eq\" value=\"0\" /></filter></entity></fetch>", accountName);
                    SavedQuery template = new SavedQuery();
                    template.FetchXml = fetchXml;
                    template.IsQuickFindQuery = false;
                    template.QueryType = SavedQueryQueryType.OfflineTemplate;
                    template.ReturnedTypeCode = Account.EntityLogicalName;
                    template.Name = "ReadOnlyFilter_" + accountName;
                    template.Description = "Sample offline template for Account entity";
                    _offlineTemplate = _serviceProxy.Create(template);

                    Console.WriteLine(" and retrieving offline template");
                    result = (SavedQuery)_serviceProxy.Retrieve(
                        SavedQuery.EntityLogicalName,
                        _offlineTemplate,
                        new ColumnSet("name", "description"));
                    Console.WriteLine("Name: {0}", result.Name);
                    Console.WriteLine("Description: {0}", result.Description);
                    Console.WriteLine();
                    //</snippetRetrieveDataFilters1>

                    //<snippetRetrieveDataFilters2>

                    // Call InstantiateFiltersRequest
                    Console.WriteLine("Retrieving user's ID and creating the template collection");
                    WhoAmIRequest whoAmI = new WhoAmIRequest();
                    Guid id = ((WhoAmIResponse)_serviceProxy.Execute(whoAmI)).UserId;
                    EntityReferenceCollection templates = new EntityReferenceCollection();
                    templates.Add(new EntityReference(
                        SavedQuery.EntityLogicalName,
                        _offlineTemplate));

                    Console.WriteLine("Activating the selected offline templates for this user");
                    InstantiateFiltersRequest request = new InstantiateFiltersRequest
                    {
                        UserId = id,
                        TemplateCollection = templates                            
                    };
                    InstantiateFiltersResponse response =
                        (InstantiateFiltersResponse)_serviceProxy.Execute(request);
                    Console.WriteLine();
                    //</snippetRetrieveDataFilters2>

                    //<snippetRetrieveDataFilters3>
                    // Call ResetUserFiltersRequest
                    Console.WriteLine("Resetting the user's offline templates to the defaults");
                    ResetUserFiltersRequest resetRequest = new ResetUserFiltersRequest
                    {
                        QueryType = SavedQueryQueryType.OfflineFilters
                    };
                    ResetUserFiltersResponse resetResponse =
                        (ResetUserFiltersResponse)_serviceProxy.Execute(resetRequest);
                    Console.WriteLine();
                    //</snippetRetrieveDataFilters3>

                    DeleteRequiredRecords(promptforDelete);
                }


            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Esempio n. 36
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 void CreateRequiredRecords()
        {
            // 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 = _serviceProxy.Create(newQueue);

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

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

            _letterId = _serviceProxy.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 = _serviceProxy.Create(item);

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

            //<snippetRemoveQueueItemWorker2>
            // Retrieve the user information.
            WhoAmIRequest whoAmIRequest = new WhoAmIRequest();
            WhoAmIResponse whoAmIResponse = (WhoAmIResponse)_serviceProxy.Execute(
                whoAmIRequest);

            ColumnSet columnSet = new ColumnSet("fullname");
            SystemUser currentUser = (SystemUser)_serviceProxy.Retrieve(
                SystemUser.EntityLogicalName,
                whoAmIResponse.UserId, columnSet);
            String currentUserName = currentUser.FullName;
            //</snippetRemoveQueueItemWorker2>

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

            _serviceProxy.Update(queueItem);

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

            return;
        }
Esempio n. 37
0
        public void ProcessWhoAmI()
        {
            bool isMultipleCallChecked = cbMultipleCalls.Checked;
            tsbCancel.Enabled = true;

            WorkAsync(new WorkAsyncInfo
            {
                Message = "Retrieving your user id...",
                Work = (w, e) =>
                {
                    // If option multiple calls is selected,
                    // the while loop is just here to illustrate the possibility to cancel
                    // a long running process made of multiple calls
                    do
                    {
                        if (w.CancellationPending)
                        {
                            e.Cancel = true;
                        }
                        var request = new WhoAmIRequest();
                        var response = (WhoAmIResponse)Service.Execute(request);

                        e.Result = response.UserId;
                    } while ((e.Cancel == false) && (isMultipleCallChecked));
                },
                ProgressChanged = e =>
                {
                    // If progress has to be notified to user, use the following method:
                    //SetWorkingMessage("Message to display");

                    // If progress has to be notified to user, through the
                    // status bar, use the following method
                    if (SendMessageToStatusBar != null)
                        SendMessageToStatusBar(this, new StatusBarMessageEventArgs(50, "progress at 50%"));
                },
                PostWorkCallBack = e =>
                {
                    tsbCancel.Enabled = false;
                    if (!e.Cancelled)
                    {
                        MessageBox.Show(string.Format("You are {0}", (Guid)e.Result));
                    }
                },
                AsyncArgument = null,
                IsCancelable = true,
                MessageWidth = 340,
                MessageHeight = 150
            });
        }
Esempio n. 38
0
        /// <summary>
        /// This sample demonstrates how to audit user access to Microsoft Dynamics CRM.
        /// The sample first enables user access auditing on an organization. Next, it
        /// creates and modifies an entity. Finally, the sample displays a report of the
        /// audited information.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            _sampleStartTime = DateTime.Now;
            using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
            {
                // This statement is required to enable early-bound type support.
                _serviceProxy.EnableProxyTypes();

                #region Enable Auditing

                // Enable auditing on the organization and for user access by editing the
                // organization's settings.
                // First, get the organization's ID from the system user record.
                var  whoAmIReq = new WhoAmIRequest();
                var  whoAmIRes = (WhoAmIResponse)_serviceProxy.Execute(whoAmIReq);
                Guid orgId     = whoAmIRes.OrganizationId;
                _systemUserId = whoAmIRes.UserId;

                // Next, retrieve the organization's record.
                var org = (Organization)_serviceProxy.Retrieve(
                    Organization.EntityLogicalName, orgId,
                    new ColumnSet("organizationid", "isauditenabled", "isuseraccessauditenabled", "useraccessauditinginterval"));

                // Finally, enable auditing on the organization, including auditing for
                // user access.
                bool organizationAuditingFlag = org.IsAuditEnabled.Value;
                bool userAccessAuditingFlag   = org.IsUserAccessAuditEnabled.Value;
                if (!organizationAuditingFlag || !userAccessAuditingFlag)
                {
                    org.IsAuditEnabled           = true;
                    org.IsUserAccessAuditEnabled = true;
                    _serviceProxy.Update(org);
                    Console.WriteLine("Enabled auditing for the organization and for user access.");
                    Console.WriteLine("Auditing interval is set to {0} hours.", org.UserAccessAuditingInterval);
                }
                else
                {
                    Console.WriteLine("Auditing was enabled before the sample began, so no auditing settings were changed.");
                }

                // Enable auditing on the account entity, since no audits will be created
                // when we create/update an account entity, otherwise.
                var oldAccountAuditing = EnableEntityAuditing(Account.EntityLogicalName, true);

                #endregion Enable Auditing

                #region Make Audited Service Calls

                CreateRequiredRecords();

                // Make an update request to the Account entity to be tracked by auditing.
                var newAccount = new Account();
                newAccount.AccountId           = _newAccountId;
                newAccount.AccountNumber       = "1-A";
                newAccount.AccountCategoryCode = new OptionSetValue(
                    (int)AccountAccountCategoryCode.PreferredCustomer);
                newAccount.Telephone1 = "555-555-5555";

                _serviceProxy.Update(newAccount);

                Console.WriteLine("Created an account and made updates which should be captured by auditing.");

                #endregion Make Audited Service Calls

                #region Revert auditing

                // Set the organization and account auditing flags back to the old values
                if (!organizationAuditingFlag || !userAccessAuditingFlag)
                {
                    // Only revert them if they were actually changed to begin with.
                    org.IsAuditEnabled           = organizationAuditingFlag;
                    org.IsUserAccessAuditEnabled = userAccessAuditingFlag;
                    _serviceProxy.Update(org);
                    Console.WriteLine("Reverted organization and user access auditing to their previous values.");
                }
                else
                {
                    Console.WriteLine("Auditing was enabled before the sample began, so no auditing settings were reverted.");
                }

                // Revert the account entity auditing.
                EnableEntityAuditing(Account.EntityLogicalName, oldAccountAuditing);

                #endregion Revert auditing

                #region Show Audited Records

                // Select all columns for convenience.
                var query = new QueryExpression(Audit.EntityLogicalName)
                {
                    ColumnSet = new ColumnSet(true),
                    Criteria  = new FilterExpression(LogicalOperator.And)
                };

                // Only retrieve audit records that track user access.
                query.Criteria.AddCondition("action", ConditionOperator.In,
                                            (int)AuditAction.UserAccessAuditStarted,
                                            (int)AuditAction.UserAccessAuditStopped,
                                            (int)AuditAction.UserAccessviaWebServices,
                                            (int)AuditAction.UserAccessviaWeb);

                // Change this to false in order to retrieve audit records for all users
                // when running the sample.
                var filterAuditsRetrievedByUser = true;
                if (filterAuditsRetrievedByUser)
                {
                    // Only retrieve audit records for the current user or the "SYSTEM"
                    // user.
                    var userFilter = new FilterExpression(LogicalOperator.Or);
                    userFilter.AddCondition(
                        "userid", ConditionOperator.Equal, _systemUserId);
                    userFilter.AddCondition(
                        "useridname", ConditionOperator.Equal, "SYSTEM");
                }
                // Only retrieve records for this sample run, so that we don't get too
                // many results if auditing was enabled previously.
                query.Criteria.AddCondition(
                    "createdon", ConditionOperator.GreaterEqual, _sampleStartTime);

                var results = _serviceProxy.RetrieveMultiple(query);
                Console.WriteLine("Retrieved audit records:");
                foreach (Audit audit in results.Entities)
                {
                    Console.Write("\r\n  Action: {0},  User: {1},"
                                  + "\r\n    Created On: {2}, Operation: {3}",
                                  (AuditAction)audit.Action.Value,
                                  audit.UserId.Name,
                                  audit.CreatedOn.Value.ToLocalTime(),
                                  (AuditOperation)audit.Operation.Value);

                    // Display the name of the related object (which will be the user
                    // for audit records with Action UserAccessviaWebServices.
                    if (!String.IsNullOrEmpty(audit.ObjectId.Name))
                    {
                        Console.WriteLine(
                            ",\r\n    Related Record: {0}", audit.ObjectId.Name);
                    }
                    else
                    {
                        Console.WriteLine();
                    }
                }

                #endregion Show Audited Records

                DeleteRequiredRecords(promptforDelete);
            }
        }
        private void Connect_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(Name.Text))
            {
                MessageBox.Show("Enter A Name");
                return;
            }

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

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

                    OrgId = wResponse.OrganizationId.ToString();

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

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

                    DialogResult = true;
                    Close();
                }
            }
            catch (Exception)
            {
                //TODO: handle error
                MessageBox.Show("Error Connecting to CRM");
            }
        }
Esempio n. 40
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

                    // Get a system user to use as the sender.
                    var emailSenderRequest  = new WhoAmIRequest();
                    var emailSenderResponse =
                        service.Execute(emailSenderRequest) as WhoAmIResponse;

                    // Set trackingId for bulk mail request.
                    Guid trackingId = Guid.NewGuid();

                    var bulkMailRequest = new SendBulkMailRequest()
                    {
                        // Create a query expression for the bulk operation to use to retrieve
                        // the contacts in the email list.
                        Query = new QueryExpression()
                        {
                            EntityName = Contact.EntityLogicalName,
                            ColumnSet  = new ColumnSet(new String[] { "contactid" }),
                            Criteria   = new FilterExpression()
                            {
                                Conditions =
                                {
                                    new ConditionExpression("contactid", ConditionOperator.In, _contactsIds)
                                }
                            }
                        },
                        // Set the Sender.
                        Sender = new EntityReference(SystemUser.EntityLogicalName, emailSenderResponse.UserId),
                        // Set the RegardingId - this field is required.
                        //RegardingId = Guid.Empty,
                        //RegardingType = SystemUser.EntityLogicalName,

                        // Use a built-in Microsoft Dynamics CRM email template.
                        // NOTE: The email template's "template type" must match the type of
                        // customers in the email list.  Our list contains contacts, so our
                        // template must be for contacts.
                        TemplateId = new Guid("07B94C1D-C85F-492F-B120-F0A743C540E6"),
                        RequestId  = trackingId
                    };

                    // Execute the async bulk email request
                    var resp = (SendBulkMailResponse)
                               service.Execute(bulkMailRequest);

                    Console.WriteLine("  Sent Bulk Email.");
                    #endregion

                    #region Monitoring SendBulkEmail

                    Console.WriteLine();
                    Console.WriteLine("Starting monitoring process..");

                    // Now that we've executed the bulk operation, we need to retrieve it
                    // using our tracking Id.

                    var bulkQuery = new QueryByAttribute()
                    {
                        EntityName = AsyncOperation.EntityLogicalName,
                        ColumnSet  = new ColumnSet(new string[] { "requestid" }),
                        Attributes = { "requestid" },
                        Values     = { trackingId }
                    };


                    // Retrieve the bulk email async operation.
                    EntityCollection aResponse = service.RetrieveMultiple(bulkQuery);


                    Console.WriteLine("  Retrieved Bulk Email Async Operation.");

                    // Monitor the async operation via polling.
                    int secondsTicker = ARBITRARY_MAX_POLLING_TIME;

                    AsyncOperation createdBulkMailOperation = null;

                    Console.WriteLine("  Checking operation's state for " + ARBITRARY_MAX_POLLING_TIME + " seconds.");
                    Console.WriteLine();

                    while (secondsTicker > 0)
                    {
                        // Make sure the async operation was retrieved.
                        if (aResponse.Entities.Count > 0)
                        {
                            // Grab the one bulk operation that has been created.
                            createdBulkMailOperation = (AsyncOperation)aResponse.Entities[0];

                            // Check the operation's state.
                            if (createdBulkMailOperation.StateCode.Value !=
                                AsyncOperationState.Completed)
                            {
                                // The operation has not yet completed.
                                // Wait a second for the status to change.
                                System.Threading.Thread.Sleep(1000);
                                secondsTicker--;

                                // Retrieve a fresh version the bulk delete operation.
                                aResponse = service.RetrieveMultiple(bulkQuery);
                            }
                            else
                            {
                                // Stop polling because the operation's state is now complete.
                                secondsTicker = 0;
                            }
                        }
                        else
                        {
                            // Wait a second for the async operation to activate.
                            System.Threading.Thread.Sleep(1000);
                            secondsTicker--;

                            // Retrieve the entity again
                            aResponse = service.RetrieveMultiple(bulkQuery);
                        }
                    }

                    // When the bulk email operation has completed, all sent emails will
                    // have a status of "Pending Send" and will be picked up by your email
                    // router.  Alternatively, you can then use BackgroundSendEmail to download
                    // all the emails created with the SendBulkEmail message.
                    // See the BackgroundSendEmail sample for an example.
                    #endregion

                    #region Check success

                    // Validate async operation succeeded
                    if (createdBulkMailOperation.StateCode.Value == AsyncOperationState.Completed)
                    {
                        Console.WriteLine("Operation Completed.");
                    }
                    else
                    {
                        Console.WriteLine("Operation not completed yet.");
                    }


                    #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. 41
0
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,
                                                                     serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    String ldapPath = String.Empty;
                    Guid businessUnitId;

                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // Call this method to create any data that this sample requires.
                    CreateRequiredRecords();

                    // Retrieve the sales people that will be added to the team.
                    salesPersons = SystemUserProvider.RetrieveSalespersons(_serviceProxy, ref ldapPath);

                    // Get the ID's of the current user and business unit.
                    var who = new WhoAmIRequest();
                    var whoResponse = (WhoAmIResponse)_serviceProxy.Execute(who);
                    _currentUserId = whoResponse.UserId;
                    businessUnitId = whoResponse.BusinessUnitId;

                    //<snippetCreateAndShareAccessTeam1>
                    // Create a access team.
                    var team = new Team
                    {
                        AdministratorId = new EntityReference(
                            "systemuser", _currentUserId),
                        Name = "UserAccess Test Team",
                        BusinessUnitId = new EntityReference(
                            "businessunit", businessUnitId),
                        TeamType = new OptionSetValue((int)TeamTeamType.Access),
                    };

                    _teamId = _serviceProxy.Create(team);
                    Console.WriteLine("Created an access team named '{0}'.", team.Name);

                    // Add two sales people to the access team.
                    var addToTeamRequest = new AddMembersTeamRequest
                    {
                        TeamId = _teamId,
                        MemberIds = new[] { salesPersons[0], salesPersons[1] }
                    };
                    _serviceProxy.Execute(addToTeamRequest);
                    Console.WriteLine("Added two sales people to the team.");
                    
                    // Grant the team read/write access to an account.
                    var accountReference = new EntityReference(Account.EntityLogicalName, _accountId);
                    var teamReference = new EntityReference(Team.EntityLogicalName, _teamId);
                    var grantAccessRequest = new GrantAccessRequest
                    {
                        PrincipalAccess = new PrincipalAccess
                        {
                            AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess,
                            Principal = teamReference
                        },
                        Target = accountReference
                    };
                    _serviceProxy.Execute(grantAccessRequest);
                    Console.WriteLine("Granted read/write access on the account record to the team.");
                    //</snippetCreateAndShareAccessTeam1>

                    // Retrieve and display access information for the account.
                    RetrieveAndDisplayEntityAccess(accountReference);

                    // Display the account access for the team and its members.
                    var currentUserReference = new EntityReference(
                        SystemUser.EntityLogicalName, _currentUserId);
                    RetrieveAndDisplayPrincipalAccess(accountReference, currentUserReference,
                        "Current User");
                    var firstSalesPersonReference = new EntityReference(
                        SystemUser.EntityLogicalName, salesPersons[0]);
                    RetrieveAndDisplayPrincipalAccess(accountReference, firstSalesPersonReference,
                        "Sales Person");
                    var secondSalesPersonReference = new EntityReference(
                        SystemUser.EntityLogicalName, salesPersons[1]);
                    RetrieveAndDisplayPrincipalAccess(accountReference, secondSalesPersonReference,
                        "Sales Person");
                    
                    // Delete all records created by this sample.
                    DeleteRequiredRecords(promptForDelete);
                }
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Esempio n. 42
0
        /// <summary>
        /// Creates any entity records that this sample requires.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            // Create a unique identifier for this sample for preventing name conflicts.
            var sampleIdentifier = Guid.NewGuid();

            // Retrieve/create the system users to use for the sample.
            var ldapPath = String.Empty;

            _systemUserIds = SystemUserProvider.RetrieveDelegates(
                service, ref ldapPath);

            // Retrieve the root business unit to use for creating the team for the
            // sample.
            var businessUnitQuery = new QueryExpression
            {
                EntityName = BusinessUnit.EntityLogicalName,
                ColumnSet  = new ColumnSet("businessunitid"),
                Criteria   = new FilterExpression()
            };

            businessUnitQuery.Criteria.AddCondition("parentbusinessunitid",
                                                    ConditionOperator.Null);
            var businessUnitResult = service.RetrieveMultiple(businessUnitQuery);
            var businessUnit       = businessUnitResult.Entities[0].ToEntity <BusinessUnit>();

            // Get the GUID of the current user.
            var who         = new WhoAmIRequest();
            var whoResponse = (WhoAmIResponse)service.Execute(who);

            _currentUserId = whoResponse.UserId;

            // Create a team for use in the sample.
            var team = new Team
            {
                AdministratorId = new EntityReference(
                    "systemuser", _currentUserId),
                Name           = String.Format("User Access Sample Team {0}", sampleIdentifier),
                BusinessUnitId = businessUnit.ToEntityReference()
            };

            _teamId = service.Create(team);

            // Add the second user to the newly created team.
            var addToTeamRequest = new AddMembersTeamRequest
            {
                TeamId    = _teamId,
                MemberIds = new[] { _systemUserIds[1] }
            };

            service.Execute(addToTeamRequest);

            // Create a account for use in the sample.
            var account = new Account
            {
                Name = "User Access Sample Company",
            };

            _accountId = service.Create(account);

            // Create a task to associate to the account.
            var accountReference = new EntityReference(Account.EntityLogicalName, _accountId);
            var task             = new Task
            {
                Subject           = "User Access Sample Task",
                RegardingObjectId = accountReference
            };

            _taskId = service.Create(task);

            // Create a letter to associate to the account.
            var letter = new Letter
            {
                Subject           = "User Access Sample Letter",
                RegardingObjectId = accountReference
            };

            service.Create(letter);
        }
Esempio n. 43
0
        private void WhoAmI()
        {
            WhoAmIRequest request = new WhoAmIRequest();
            WhoAmIResponse response = (WhoAmIResponse)this.service.Execute(request);

            MessageBox.Show(this, "Your ID is: " + response.UserId.ToString("B"));
        }
Esempio n. 44
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

                    // Enable auditing on the organization and for user access by editing the
                    // organization's settings.
                    // First, get the organization's ID from the system user record.

                    var  whoAmIReq = new WhoAmIRequest();
                    var  whoAmIRes = (WhoAmIResponse)service.Execute(whoAmIReq);
                    Guid orgId     = whoAmIRes.OrganizationId;
                    _systemUserId = whoAmIRes.UserId;

                    // Next, retrieve the organization's record.
                    var org = (Organization)service.Retrieve(
                        Organization.EntityLogicalName, orgId,
                        new ColumnSet("organizationid", "isauditenabled", "isuseraccessauditenabled", "useraccessauditinginterval"));

                    // Finally, enable auditing on the organization, including auditing for
                    // user access.
                    bool organizationAuditingFlag = org.IsAuditEnabled.Value;
                    bool userAccessAuditingFlag   = org.IsUserAccessAuditEnabled.Value;
                    if (!organizationAuditingFlag || !userAccessAuditingFlag)
                    {
                        org.IsAuditEnabled           = true;
                        org.IsUserAccessAuditEnabled = true;
                        service.Update(org);
                        Console.WriteLine("Enabled auditing for the organization and for user access.");
                        Console.WriteLine("Auditing interval is set to {0} hours.", org.UserAccessAuditingInterval);
                    }
                    else
                    {
                        Console.WriteLine("Auditing was enabled before the sample began, so no auditing settings were changed.");
                    }

                    // Enable auditing on the account entity, since no audits will be created
                    // when we create/update an account entity, otherwise.
                    var oldAccountAuditing = EnableEntityAuditing(service, Account.EntityLogicalName, true);

                    // Make an update request to the Account entity to be tracked by auditing.
                    var newAccount = new Account();
                    newAccount.AccountId           = _newAccountId;
                    newAccount.AccountNumber       = "1-A";
                    newAccount.AccountCategoryCode = new OptionSetValue(
                        (int)AccountAccountCategoryCode.PreferredCustomer);
                    newAccount.Telephone1 = "555-555-5555";

                    service.Update(newAccount);
                    Console.WriteLine("Created an account and made updates which should be captured by auditing.");

                    // Set the organization and account auditing flags back to the old values
                    if (!organizationAuditingFlag || !userAccessAuditingFlag)
                    {
                        // Only revert them if they were actually changed to begin with.
                        org.IsAuditEnabled           = organizationAuditingFlag;
                        org.IsUserAccessAuditEnabled = userAccessAuditingFlag;
                        service.Update(org);
                        Console.WriteLine("Reverted organization and user access auditing to their previous values.");
                    }
                    else
                    {
                        Console.WriteLine("Auditing was enabled before the sample began, so no auditing settings were reverted.");
                    }

                    // Revert the account entity auditing.
                    EnableEntityAuditing(service, Account.EntityLogicalName, oldAccountAuditing);

                    #endregion Revert auditing

                    #region Show Audited Records

                    // Select all columns for convenience.
                    var query = new QueryExpression(Audit.EntityLogicalName)
                    {
                        ColumnSet = new ColumnSet(true),
                        Criteria  = new FilterExpression(LogicalOperator.And)
                    };

                    // Only retrieve audit records that track user access.
                    query.Criteria.AddCondition("action", ConditionOperator.In,
                                                (int)AuditAction.UserAccessAuditStarted,
                                                (int)AuditAction.UserAccessAuditStopped,
                                                (int)AuditAction.UserAccessviaWebServices,
                                                (int)AuditAction.UserAccessviaWeb);

                    // Change this to false in order to retrieve audit records for all users
                    // when running the sample.
                    var filterAuditsRetrievedByUser = true;
                    if (filterAuditsRetrievedByUser)
                    {
                        // Only retrieve audit records for the current user or the "SYSTEM"
                        // user.
                        var userFilter = new FilterExpression(LogicalOperator.Or);
                        userFilter.AddCondition(
                            "userid", ConditionOperator.Equal, _systemUserId);
                        userFilter.AddCondition(
                            "useridname", ConditionOperator.Equal, "SYSTEM");
                    }
                    // Only retrieve records for this sample run, so that we don't get too
                    // many results if auditing was enabled previously.
                    query.Criteria.AddCondition(
                        "createdon", ConditionOperator.GreaterEqual, DateTime.UtcNow);

                    var results = service.RetrieveMultiple(query);
                    Console.WriteLine("Retrieved audit records:");
                    foreach (Audit audit in results.Entities)
                    {
                        Console.Write("\r\n  Action: {0},  User: {1},"
                                      + "\r\n    Created On: {2}, Operation: {3}",
                                      (AuditAction)audit.Action.Value,
                                      audit.UserId.Name,
                                      audit.CreatedOn.Value.ToLocalTime(),
                                      (AuditOperation)audit.Operation.Value);

                        // Display the name of the related object (which will be the user
                        // for audit records with Action UserAccessviaWebServices.
                        if (!String.IsNullOrEmpty(audit.ObjectId.Name))
                        {
                            Console.WriteLine(
                                ",\r\n    Related Record: {0}", audit.ObjectId.Name);
                        }
                        else
                        {
                            Console.WriteLine();
                        }
                    }

                    #endregion Show Audited Records

                    #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();
            }
        }
Esempio n. 45
0
        /// <summary>
        /// Creates any entity records that this sample requires.
        /// </summary>
        public void CreateRequiredRecords()
        {
            // Create a unique identifier for this sample for preventing name conflicts.
            var sampleIdentifier = Guid.NewGuid();

            // Retrieve/create the system users to use for the sample.
            var ldapPath = String.Empty;
            _systemUserIds = SystemUserProvider.RetrieveDelegates(
                _serviceProxy, ref ldapPath);

            // Retrieve the root business unit to use for creating the team for the
            // sample.
            var businessUnitQuery = new QueryExpression
            {
                EntityName = BusinessUnit.EntityLogicalName,
                ColumnSet = new ColumnSet("businessunitid"),
                Criteria = new FilterExpression()
            };

            businessUnitQuery.Criteria.AddCondition("parentbusinessunitid",
                ConditionOperator.Null);
            var businessUnitResult = _serviceProxy.RetrieveMultiple(businessUnitQuery);
            var businessUnit = businessUnitResult.Entities[0].ToEntity<BusinessUnit>();

            // Get the GUID of the current user.
            var who = new WhoAmIRequest();
            var whoResponse = (WhoAmIResponse)_serviceProxy.Execute(who);
            _currentUserId = whoResponse.UserId;

            // Create a team for use in the sample.
            var team = new Team
            {
                AdministratorId = new EntityReference(
                    "systemuser", _currentUserId),
                Name = String.Format("User Access Sample Team {0}", sampleIdentifier),
                BusinessUnitId = businessUnit.ToEntityReference()
            };
            _teamId = _serviceProxy.Create(team);

            // Add the second user to the newly created team.
            var addToTeamRequest = new AddMembersTeamRequest
            {
                TeamId = _teamId,
                MemberIds = new[] { _systemUserIds[1] }
            };
            _serviceProxy.Execute(addToTeamRequest);

            // Create a lead for use in the sample.
            var lead = new Lead
            {
                CompanyName = "User Access Sample Company",
                FirstName = "Sample",
                LastName = "Lead",
                Subject = "User Access Sample Lead",
            };
            _leadId = _serviceProxy.Create(lead);

            // Create a task to associate to the lead.
            var leadReference = new EntityReference(Lead.EntityLogicalName, _leadId);
            var task = new Task
            {
                Subject = "User Access Sample Task",
                RegardingObjectId = leadReference
            };
            _taskId = _serviceProxy.Create(task);

            // Create a letter to associate to the lead.
            var letter = new Letter
            {
                Subject = "User Access Sample Letter",
                RegardingObjectId = leadReference
            };
            _serviceProxy.Create(letter);
        }
Esempio n. 46
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 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();
            }
        }
        private void WorkerDoWork(object sender, DoWorkEventArgs e)
        {
            var request = new WhoAmIRequest();
            var response = (WhoAmIResponse)service.Execute(request);

            ((BackgroundWorker)sender).ReportProgress(0, "Your used id has been retrieved!");

            e.Result = response.UserId;
        }
Esempio n. 48
0
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Initiate the method to create any data that this sample requires.
        /// Book an appointment.
        /// Optionally delete any entity records that were created for this sample.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // Call the method to create any data that this sample requires.
                    CreateRequiredRecords();

                    //<snippetBookAppointment1>

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

                    // Create the ActivityParty instance.
                    ActivityParty party = new ActivityParty
                    {
                        PartyId = new EntityReference(SystemUser.EntityLogicalName, userResponse.UserId)
                    };

                    // Create the appointment instance.
                    Appointment appointment = new Appointment
                    {
                        Subject           = "Test Appointment",
                        Description       = "Test Appointment created using the BookRequest Message.",
                        ScheduledStart    = DateTime.Now.AddHours(1),
                        ScheduledEnd      = DateTime.Now.AddHours(2),
                        Location          = "Office",
                        RequiredAttendees = new ActivityParty[] { party },
                        Organizer         = new ActivityParty[] { party }
                    };

                    // Use the Book request message.
                    BookRequest book = new BookRequest
                    {
                        Target = appointment
                    };
                    BookResponse booked = (BookResponse)_serviceProxy.Execute(book);
                    _appointmentId = booked.ValidationResult.ActivityId;

                    // Verify that the appointment has been scheduled.
                    if (_appointmentId != Guid.Empty)
                    {
                        Console.WriteLine("Succesfully booked {0}.", appointment.Subject);
                    }

                    //</snippetBookAppointment1>

                    DeleteRequiredRecords(promptForDelete);
                }
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Esempio n. 49
0
        /// <summary>
        /// Tests the specified connection
        /// </summary>
        /// <param name="service">Organization service</param>
        public void TestConnection(IOrganizationService service)
        {
            try
            {
                SendStepChange("Testing connection...");

                var request = new WhoAmIRequest();
                service.Execute(request);
            }
            catch (Exception error)
            {
                throw new Exception("Test connection failed: " + CrmExceptionHelper.GetErrorMessage(error, false));
            }
        }
Esempio n. 50
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// </summary>
        public void CreateRequiredRecords()
        {
            // Get the current user's information.
            WhoAmIRequest  userRequest  = new WhoAmIRequest();
            WhoAmIResponse userResponse = (WhoAmIResponse)_serviceProxy.Execute(userRequest);

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

            _vanId = _serviceProxy.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 = _serviceProxy.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 = _serviceProxy.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 = _serviceProxy.Create(plumberService);

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