コード例 #1
0
        /// <summary>
        /// Instantiates an instance of the proxy class
        /// </summary>
        /// <param name="proxy">Proxy that will be used to authenticate the user</param>
        public AutoRefreshSecurityToken(TProxy proxy)
        {
            if (null == proxy)
            {
                throw new ArgumentNullException("proxy");
            }

            this._proxy = proxy;

            _expirationWindow = SitecoreUtility.GetSitecoreSetting <int>("AlphaSolutions.ExtendedCRMProvider.V5.TokenExpirationWindow", 15);
        }
コード例 #2
0
        /// <summary>
        /// Method to get users in given Role. in CRM Marketing list.
        /// This method has been customized to support dynamic lists.
        /// </summary>
        /// <param name="roleName"></param>
        /// <returns></returns>
        public override string[] GetUsersInRole(string roleName)
        {
            //setting that disabled the dynamic list functionality.
            if (SitecoreUtility.GetSitecoreSetting <bool>("AlphaSolutions.ExtendedCRMProvider.Disable.DynamicLists",
                                                          false))
            {
                return(base.GetUsersInRole(roleName));
            }

            Assert.ArgumentNotNull(roleName, "roleName");
            ConditionalLog.Info(string.Format("GetUsersInRole({0}). Started.", roleName), this, TimerAction.Start, "getUsersInRole");
            string text = base.CacheService.MembersCache.Get(roleName);

            if (text != null)
            {
                ConditionalLog.Info(string.Format("GetUsersInRole({0}). Finished (users have been retrieved from cache).", roleName), this, TimerAction.Stop, "getUsersInRole");
                return(text.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries));
            }

            // set up a query for the list to check type
            Microsoft.Xrm.Sdk.Query.ColumnSet columnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet(new string[] { "listname", "query", "type" });

            Microsoft.Xrm.Sdk.Query.QueryExpression query = new Microsoft.Xrm.Sdk.Query.QueryExpression();
            query.ColumnSet = columnSet;

            Microsoft.Xrm.Sdk.Query.ConditionExpression listnameCondition = new Microsoft.Xrm.Sdk.Query.ConditionExpression();
            listnameCondition.AttributeName = "listname";
            listnameCondition.Operator      = Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal;
            listnameCondition.Values.Add(roleName);

            Microsoft.Xrm.Sdk.Query.FilterExpression filterList = new Microsoft.Xrm.Sdk.Query.FilterExpression();
            filterList.Conditions.Add(listnameCondition);
            filterList.FilterOperator = Microsoft.Xrm.Sdk.Query.LogicalOperator.And;
            query.EntityName          = "list";
            query.Criteria            = filterList;

            // Execute the query
            Microsoft.Xrm.Sdk.Messages.RetrieveMultipleRequest req = new Microsoft.Xrm.Sdk.Messages.RetrieveMultipleRequest();
            req.Query = query;

            Microsoft.Xrm.Sdk.Messages.RetrieveMultipleResponse res
                = (Microsoft.Xrm.Sdk.Messages.RetrieveMultipleResponse) this.OrganizationService.Execute(req);

            if (res != null && res.EntityCollection != null && res.EntityCollection.Entities.Count > 0)
            {
                Entity myList = res.EntityCollection.Entities[0];
                if (myList.Attributes.Keys.Contains("query"))
                {
                    // Define the fetch attributes.
                    // Set the number of records per page to retrieve.
                    int fetchCount = Settings.FetchThrottlingPageSize;
                    // Initialize the page number.
                    int pageNumber = 1;
                    // Initialize the number of records.
                    int recordCount = 0;
                    // Specify the current paging cookie. For retrieving the first page,
                    // pagingCookie should be null.
                    string pagingCookie = null;

                    //Convert fetchXML to Query Expression
                    var xml = myList["query"].ToString();

                    HashSet <string> hashSet = new HashSet <string>();


                    try
                    {
                        while (true)
                        {
                            string xmlpaging = CreateXml(xml, pagingCookie, pageNumber, fetchCount, Settings.UniqueKeyProperty);
                            Microsoft.Xrm.Sdk.Query.FetchExpression f       = new Microsoft.Xrm.Sdk.Query.FetchExpression(xmlpaging);
                            RetrieveMultipleRequest retrieveMultipleRequest = new RetrieveMultipleRequest();
                            retrieveMultipleRequest.Query = f;
                            RetrieveMultipleResponse retrieveMultipleResponse = (RetrieveMultipleResponse)this.OrganizationService.Execute(retrieveMultipleRequest);
                            if (retrieveMultipleResponse != null && retrieveMultipleResponse.EntityCollection != null)
                            {
                                ConditionalLog.Info(string.Format("GetUsersInRole({0}). Retrieved {1} users from CRM.", roleName, retrieveMultipleResponse.EntityCollection.Entities.Count), this, TimerAction.Tick, "getUsersInRole");
                                foreach (Entity current in retrieveMultipleResponse.EntityCollection.Entities)
                                {
                                    try
                                    {
                                        base.CacheService.UserCache.Add(this.ContactToUserConverter.Convert(current));
                                        hashSet.Add((string)current[Settings.UniqueKeyProperty]);
                                    }
                                    catch (Exception e)
                                    {
                                        ConditionalLog.Error(string.Format("GetUsersInRole({0}). Error in converting contact to user. Number of attributes gotten: {1}", current.LogicalName, current.Attributes.Count), e, this);
                                    }
                                }
                                // Check for morerecords, if it returns 1.
                                if (retrieveMultipleResponse.EntityCollection.MoreRecords)
                                {
                                    // Increment the page number to retrieve the next page.
                                    pageNumber++;
                                }
                                else
                                {
                                    // If no more records in the result nodes, exit the loop.
                                    break;
                                }
                                pagingCookie = retrieveMultipleResponse.EntityCollection.PagingCookie;
                            }
                        }
                        var ret = hashSet.ToArray <string>();
                        base.CacheService.MembersCache.Add(roleName, string.Join("|", ret));
                        return(ret);
                    }
                    catch (System.Exception sourceException)
                    {
                        ConditionalLog.Error(string.Format("Couldn't get contacts of {0} marketing list from CRM.", roleName), sourceException, this);
                    }
                }
                else
                {
                    return(base.GetUsersInRole(roleName));
                }
            }
            return(new string[0]);
        }
コード例 #3
0
        protected T Resolve <T>(ConfigurationSettings settings)
        {
            //setting to disable customized code all together
            if (SitecoreUtility.GetSitecoreSetting <bool>("AlphaSolutions.ExtendedCRMProvider.Disable.Customizations", false))
            {
                return(base.Resolve <T>(settings));
            }

            //have the original base class handle older API versions.
            if (settings.ApiVersion != ApiVersion.V5)
            {
                return(base.Resolve <T>(settings));
            }

            if (_unityContainer == null)
            {
                lock (Locker)
                {
                    if (_unityContainer == null)
                    {
                        UnityContainer container = new UnityContainer();
                        switch (settings.ApiVersion)
                        {
                        case ApiVersion.V3:
                        {
                            throw new NotImplementedException("V3 has not yet been implemented. Should be handled by base class.");
                            break;
                        }

                        case ApiVersion.V4:
                        {
                            throw new NotImplementedException("V3 has not yet been implemented. Should be handled by base class.");
                            break;
                        }

                        case ApiVersion.V5:
                        {
                            var rv3 = new CrmServiceCreatorV5();
                            container.RegisterInstance <IOrganizationService>(
                                rv3.CreateOrganizationService(settings),
                                new ContainerControlledLifetimeManager())
                            .RegisterType <ICacheService, CacheService>(
                                new ContainerControlledLifetimeManager(), new InjectionMember[0])
                            .RegisterType <IContactToUserConverterV5, ContactToUserConverterV5>(
                                new ContainerControlledLifetimeManager(), new InjectionMember[0])
                            .RegisterType <IMarketingListToRoleConverterV5, MarketingListToRoleConverterV5>(
                                new ContainerControlledLifetimeManager(), new InjectionMember[0])
                            .RegisterType <UserRepositoryBase, UserRepositoryV5>(
                                new ContainerControlledLifetimeManager(), new InjectionMember[0])
                            .RegisterType <RoleRepositoryBase, RoleRepositoryV5>(
                                new ContainerControlledLifetimeManager(), new InjectionMember[0])
                            .RegisterType <ProfileRepositoryBase, ProfileRepositoryV5>(
                                new ContainerControlledLifetimeManager(), new InjectionMember[0])
                            .RegisterType
                            <EntityRepositoryBase,
                             EntityRepository>(
                                new ContainerControlledLifetimeManager(), new InjectionMember[0]);
                            break;
                        }
                        }
                        _unityContainer = container;
                    }
                }
            }
            return(_unityContainer.Resolve <T>(new ResolverOverride[0]));
        }
コード例 #4
0
        public IOrganizationService CreateOrganizationService(ConfigurationSettings settings)
        {
            Assert.ArgumentNotNull(settings, "settings");
            ConditionalLog.Info("CreateOrganizationService(settings). Started.", this, TimerAction.Start, "createOrganizationService");
            IOrganizationService service = null;

            try
            {
                IServiceManagement <IOrganizationService> serviceManagement = ServiceConfigurationFactory.CreateManagement <IOrganizationService>(new Uri(settings.Url));
                AuthenticationCredentials authenticationCredentials         = new AuthenticationCredentials();
                switch (serviceManagement.AuthenticationType)
                {
                case AuthenticationProviderType.ActiveDirectory:
                    authenticationCredentials.ClientCredentials.Windows.ClientCredential = CrmHelper.CreateNetworkCredential(settings.User, settings.Password);
                    service = new OrganizationServiceProxy(serviceManagement, authenticationCredentials.ClientCredentials);
                    break;

                case AuthenticationProviderType.Federation:
                case AuthenticationProviderType.LiveId:
                case AuthenticationProviderType.OnlineFederation:
                {
                    authenticationCredentials.ClientCredentials.UserName.UserName = settings.User;
                    authenticationCredentials.ClientCredentials.UserName.Password = settings.Password;

                    AuthenticationCredentials credentials2 = serviceManagement.Authenticate(authenticationCredentials);

                    //setting to be able to configure using the custom token service proxy
                    if (
                        SitecoreUtility.GetSitecoreSetting <bool>(
                            "AlphaSolutions.ExtendedCRMProvider.V5.Disable.AuthenticationCustomization", false))
                    {
                        service = new CRMSecurityProvider.Repository.V5.ManagedTokenOrganizationServiceProxy(serviceManagement, credentials2.SecurityTokenResponse);
                    }
                    else
                    {
                        service = new ManagedTokenOrganizationServiceProxy(serviceManagement,
                                                                           credentials2.SecurityTokenResponse, authenticationCredentials);
                    }
                    break;
                }
                }

                if (service == null)
                {
                    ConditionalLog.Error("CreateOrganizationService(settings). service could not be initialized.", this);
                    return(null);
                }

                service.Execute(new WhoAmIRequest());
                ConditionalLog.Info("CreateOrganizationService(settings). CRM organization service has been created.", this, TimerAction.Tick, "createOrganizationService");
            }
            catch (Exception exception)
            {
                ConditionalLog.Error("Couldn't create CRM organization service.", exception, this);
                return(null);
            }
            finally
            {
                ConditionalLog.Info("CreateOrganizationService(settings). Finished.", this, TimerAction.Stop, "createOrganizationService");
            }
            return(service);
        }