override protected void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (Items.Count > 0)
            {
                return;
            }

            Items.Add(new ListItem(string.Empty, string.Empty));

            var context = CrmConfigurationManager.CreateContext(ContextName);

            var subjects = context.CreateQuery("subject").ToList();

            var parents = subjects.Where(s => s.GetAttributeValue <EntityReference>("parentsubject") == null).OrderBy(s => s.GetAttributeValue <string>("title"));

            foreach (var parent in parents)
            {
                if (parent == null)
                {
                    continue;
                }

                Items.Add(new ListItem(parent.GetAttributeValue <string>("title"), parent.Id.ToString()));

                var parentId = parent.Id;

                var children = subjects.Where(s => s.GetAttributeValue <EntityReference>("parentsubject") != null && s.GetAttributeValue <EntityReference>("parentsubject").Id == parentId).OrderBy(s => s.GetAttributeValue <string>("title"));

                AddChildItems(subjects, children, 1);
            }
        }
        protected virtual IEnumerable <IOrganizationServiceCache> GetServiceCaches()
        {
            var section = CrmConfigurationManager.GetCrmSection();

            var elements = section.ServiceCache.Cast <OrganizationServiceCacheElement>().ToList();

            if (!elements.Any())
            {
                yield return(CrmConfigurationManager.CreateServiceCache(null, (string)null, true));
            }
            else
            {
                // ignore service cache objects that are nested in a composite service cache

                var ignored = (
                    from element in elements
                    let inner = element.Parameters["innerServiceCacheName"]
                                where !string.IsNullOrWhiteSpace(inner)
                                select inner).ToList();

                foreach (var element in elements.Where(e => !ignored.Contains(e.Name)))
                {
                    var connectionId = GetConnectionId(element.Parameters);

                    yield return(CrmConfigurationManager.CreateServiceCache(element.Name, connectionId, true));
                }
            }
        }
예제 #3
0
        protected virtual string GetConnectionStringName(string name, NameValueCollection config)
        {
            var contextName          = GetContextName(name, config);
            var connectionStringName = CrmConfigurationManager.GetConnectionStringNameFromContext(contextName);

            return(connectionStringName);
        }
        public WebCrmEntityIndex(Directory directory, Analyzer analyzer, Version version, string indexQueryName)
        {
            if (directory == null)
            {
                throw new ArgumentNullException("directory");
            }

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

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

            Directory      = directory;
            Version        = version;
            IndexQueryName = indexQueryName;

            Name = string.IsNullOrEmpty(_dataContextName)
                                ? CrmConfigurationManager.GetCrmSection().Contexts.Current.Name
                                : _dataContextName;

            _defaultAnalyzer = analyzer;

            Analyzer = GetAnalyzer();
        }
예제 #5
0
        private static ConnectionStringSettings GetConnectionStringSettings(string connectionStringName)
        {
            var settings = ConfigurationManager.ConnectionStrings[connectionStringName];

            if (settings == null)
            {
                if (connectionStringName == "SharePoint")
                {
                    // Try to use the CRM connection string "Xrm"
                    if (ConfigurationManager.ConnectionStrings.Count != 0)
                    {
                        settings = ConfigurationManager.ConnectionStrings["Xrm"];
                    }
                    else if (CrmConfigurationManager.GetCrmSection().ConnectionStrings.Count != 0)
                    {
                        settings = CrmConfigurationManager.GetCrmSection().ConnectionStrings["Xrm"];
                    }
                }

                if (settings == null)
                {
                    throw new ConfigurationErrorsException("Unable to find a connection string with the name {0}.".FormatWith(connectionStringName));
                }
            }

            return(settings);
        }
예제 #6
0
        /// <summary>
        /// Retrieves the <see cref="ObjectCache"/>.
        /// </summary>
        /// <param name="objectCacheName">The configuration name of the cache.</param>
        /// <returns>The cache.</returns>
        private static ObjectCache GetCache(string objectCacheName)
        {
            var cache = CrmConfigurationManager.GetObjectCaches(objectCacheName).FirstOrDefault()
                        ?? CrmConfigurationManager.CreateObjectCache(objectCacheName);

            return(cache);
        }
예제 #7
0
        internal override IEnumerable <XObject> ToBody(HttpContext context, ProductInfo product)
        {
            var assemblies = ToSection("Assemblies", new[] { "Name", "Version", "Location" }, () => product.Assemblies.Select(ToAssembly));
            var iis        = ToSection("IIS", new[] { "Name", "Value" }, () => ToIis(context));
            var identity   = ToSection("Identity", new[] { "Name", "Value" }, () => ToIdentity(context));
            var claims     = ToSection("Claims", new[] { "Type", "Value", "Value Type", "Issuer", "Original Issuer" }, () => ToClaims(context));
            var errors     = ToSection("Errors", new[] { "Timestamp", "Dropped", "Message" }, ToErrors);

            var connectionStringName = context.Request["connectionStringName"]
                                       ?? CrmConfigurationManager.GetConnectionStringNameFromContext(null, true)
                                       ?? "Xrm";

            if (!string.IsNullOrWhiteSpace(connectionStringName))
            {
                var connection = new CrmConnection(connectionStringName);

                using (var service = new OrganizationService(connection))
                {
                    var connectionSection = ToSection("Connection", new[] { "Name", "Value" }, () => ToConnection(connectionStringName, service));
                    var organization      = ToSection("Organization", new[] { "Name", "Value" }, () => ToOrganization(service));
                    var solutions         = ToSection("Solutions", new[] { "UniqueName", "Name", "Version", "Publisher" }, () => ToSolutions(service));
                    var portal            = ToSection("Portal", new[] { "Name", "Value" }, ToPortal);

                    return(assemblies.Concat(connectionSection).Concat(organization).Concat(solutions).Concat(portal).Concat(iis).Concat(identity).Concat(claims).Concat(errors));
                }
            }

            var connectionStringNameSection = ToSection("Connection", new[] { "Name", "Value" }, () => new[] { ToRow("ConnectionStringName", connectionStringName) });

            return(assemblies.Concat(connectionStringNameSection).Concat(iis).Concat(identity).Concat(claims).Concat(errors));
        }
예제 #8
0
        private static string GetServiceCacheName(out string connectionId)
        {
            // try the default provider

            var section        = CrmConfigurationManager.GetCrmSection();
            var defaultElement = section.ServiceCache.GetElementOrDefault(null);

            if (IsExtendedOrganizationServiceCache(defaultElement.DependencyType))
            {
                connectionId = GetConnectionId(defaultElement.Parameters);

                return(defaultElement.Name);
            }

            // return the first element that has a ServiceBusObjectCache dependency

            var element = section.ServiceCache.Cast <OrganizationServiceCacheElement>().FirstOrDefault(cache => IsExtendedOrganizationServiceCache(cache.DependencyType));

            if (element != null)
            {
                connectionId = GetConnectionId(element.Parameters);
                return(element.Name);
            }

            connectionId = null;
            return(null);
        }
        private static string GetDefaultContextName()
        {
            var section = CrmConfigurationManager.GetCrmSection();
            var element = section.Contexts.GetElementOrDefault(null);

            return(element.Name);
        }
        private static string GetConnectionId(NameValueCollection config)
        {
            var contextName          = GetContextName(config);
            var connectionStringName = CrmConfigurationManager.GetConnectionStringNameFromContext(contextName, true);
            var connection           = new CrmConnection(connectionStringName);

            return(connection.GetConnectionId());
        }
예제 #11
0
        public static CrmOrganizationServiceContext Create(string name = null)
        {
            var context = CrmConfigurationManager.CreateContext(name);

            context.MergeOption = MergeOption.NoTracking;

            return(context as CrmOrganizationServiceContext);
        }
예제 #12
0
        internal static IOrganizationServiceCache GetOrganizationServiceCache()
        {
            string connectionId;
            var    serviceCacheName = GetServiceCacheName(out connectionId);
            var    cache            = CrmConfigurationManager.CreateServiceCache(serviceCacheName, connectionId);

            return(cache);
        }
예제 #13
0
        protected override void InstantiateControlIn(HtmlControl container)
        {
            if (RenderWebResourcesInline == true)
            {
                var context = CrmConfigurationManager.CreateContext(ContextName);

                var webResource =
                    context.CreateQuery("webresource").FirstOrDefault(
                        wr => wr.GetAttributeValue <string>("name") == Metadata.WebResourceUrl);

                if (webResource == null || string.IsNullOrWhiteSpace(webResource.GetAttributeValue <string>("content")))
                {
                    var placeholder = new HtmlGenericControl("literal")
                    {
                        ID = Metadata.ControlID, Visible = Enabled
                    };

                    container.Controls.Add(placeholder);

                    return;
                }

                var htmlContent = new HtmlDocument();

                var webResourceContent = DecodeFrom64(webResource.GetAttributeValue <string>("content"));

                htmlContent.LoadHtml(webResourceContent);

                var body = htmlContent.DocumentNode.SelectSingleNode("//body");

                var literal = new HtmlGenericControl("literal")
                {
                    ID = Metadata.ControlID, Visible = Enabled
                };

                if (body != null)
                {
                    literal.InnerHtml = body.InnerHtml;

                    container.Controls.Add(literal);
                }
            }
            else
            {
                var iframe = new HtmlGenericControl("iframe")
                {
                    ID = Metadata.ControlID, Visible = Enabled
                };

                iframe.Attributes["src"]         = WebResourceRouteFormat.FormatWith(Metadata.WebResourceUrl);
                iframe.Attributes["scrolling"]   = Metadata.WebResourceScrolling;
                iframe.Attributes["frameborder"] = Metadata.WebResourceBorder ? "1" : "0";
                iframe.Attributes["height"]      = "100%";
                iframe.Attributes["width"]       = "100%";

                container.Controls.Add(iframe);
            }
        }
        protected override void InstantiateControlIn(Control container)
        {
            var dropDown = new DropDownList {
                ID = ControlID, CssClass = string.Join(" ", CssClass, Metadata.CssClass), ToolTip = Metadata.ToolTip
            };

            dropDown.Attributes.Add("onchange", "setIsDirty(this.id);");

            container.Controls.Add(dropDown);

            if (Metadata.IsRequired || Metadata.WebFormForceFieldIsRequired)
            {
                dropDown.Attributes.Add("required", string.Empty);
            }

            var context = CrmConfigurationManager.CreateContext();

            if (Metadata.ReadOnly || ((WebControls.CrmEntityFormView)container.BindingContainer).Mode == FormViewMode.ReadOnly)
            {
                AddSpecialBindingAndHiddenFieldsToPersistDisabledSelect(container, context, dropDown);
            }
            else
            {
                PopulateDropDownIfFirstLoad(context, dropDown);

                Bindings[Metadata.DataFieldName] = new CellBinding
                {
                    Get = () =>
                    {
                        Guid id;

                        if (Guid.TryParse(dropDown.SelectedValue, out id))
                        {
                            foreach (var lookupTarget in Metadata.LookupTargets)
                            {
                                var lookupTargetId = GetEntityMetadata(context, lookupTarget).PrimaryIdAttribute;

                                var foundEntity = context.CreateQuery(lookupTarget).FirstOrDefault(e => e.GetAttributeValue <Guid?>(lookupTargetId) == id);

                                if (foundEntity != null)
                                {
                                    return(new EntityReference(lookupTarget, id));
                                }
                            }
                        }

                        return(null);
                    },
                    Set = obj =>
                    {
                        var entityReference = (EntityReference)obj;
                        dropDown.SelectedValue = entityReference.Id.ToString();
                    }
                };
            }
        }
예제 #15
0
        private static ConnectionStringSettings GetConnectionStringSettings(string connectionStringName)
        {
            var settings = CrmConfigurationManager.CreateConnectionStringSettings(connectionStringName);

            if (settings == null)
            {
                throw new ConfigurationErrorsException("Unable to find a connection string with the name '{0}'.".FormatWith(connectionStringName));
            }

            return(settings);
        }
예제 #16
0
 protected virtual Type GetCrmDataContextType()
 {
     try
     {
         return(CrmConfigurationManager.GetCrmSection().Contexts.Current.DependencyType ?? typeof(OrganizationServiceContext));
     }
     catch
     {
         return(typeof(OrganizationServiceContext));
     }
 }
예제 #17
0
        private static IEnumerable <ObjectCache> GetCaches(string objectCacheName)
        {
            var caches = CrmConfigurationManager.GetObjectCaches(objectCacheName);

            if (caches.Any())
            {
                return(caches);
            }

            return(new[] { CrmConfigurationManager.CreateObjectCache(objectCacheName) });
        }
예제 #18
0
        protected static OrganizationService CreateOrganizationService(string portalName = null, bool allowDefaultFallback = false, string serviceName = null)
        {
            var portalContextElement = PortalCrmConfigurationManager.GetPortalContextElement(portalName, allowDefaultFallback);

            var contextName = !string.IsNullOrWhiteSpace(portalContextElement.ContextName)
                                ? portalContextElement.ContextName
                                : portalContextElement.Name;

            var connection = new CrmConnection(CrmConfigurationManager.GetConnectionStringNameFromContext(contextName));

            return(CrmConfigurationManager.CreateService(connection, serviceName) as OrganizationService);
        }
        /// <summary>
        /// Retrieves the configured <see cref="IOrganizationService"/>.
        /// </summary>
        /// <param name="portalName"></param>
        /// <param name="allowDefaultFallback"></param>
        /// <returns></returns>
        public virtual IOrganizationService CreateOrganizationService(string portalName = null, bool allowDefaultFallback = false)
        {
            var portalContextElement = GetPortalContextElement(portalName, allowDefaultFallback);

            var contextName = !string.IsNullOrWhiteSpace(portalContextElement.ContextName)
                                ? portalContextElement.ContextName
                                : portalContextElement.Name;

            var service = CrmConfigurationManager.CreateService(contextName, true);

            return(service);
        }
        private static int GetDefaultTimeout()
        {
            var section = CrmConfigurationManager.GetCrmSection();

            if (section != null && section.MutexTimeout != null)
            {
                var timeout = (int)section.MutexTimeout.Value.TotalMilliseconds;

                return(timeout);
            }

            return(Timeout.Infinite);
        }
예제 #21
0
        private static OptionMetadataCollection GetPipelinePhases()
        {
            var serviceContext = CrmConfigurationManager.CreateContext();

            var response = (RetrieveAttributeResponse)serviceContext.Execute(new RetrieveAttributeRequest
            {
                EntityLogicalName = "opportunity",
                LogicalName       = "salesstage"
            });

            var picklist = response.AttributeMetadata as PicklistAttributeMetadata;

            return(picklist == null ? null : picklist.OptionSet.Options);
        }
예제 #22
0
 public override IOrganizationService Create()
 {
     //try
     //{
     //if (HttpContext.Current.Request.Cookies["Branch"] != null)
     //{
     //    return CrmConfigurationManager.CreateService(new CrmConnection(HttpContext.Current.Request.Cookies["Branch"]["branch"]));
     //}
     //return CrmConfigurationManager.CreateService(new CrmConnection("Xrm"));
     //}
     //catch (System.Exception)
     //{
     return(CrmConfigurationManager.CreateService(new CrmConnection("Xrm")));
     //}
 }
예제 #23
0
        public override int GetNumberOfInactiveProfiles(ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate)
        {
            var wherePredicate = GetInactiveProfilePredicate(userInactiveSinceDate);

            if (authenticationOption != ProfileAuthenticationOption.All)
            {
                wherePredicate = CreateOrModifyWherePredicate(wherePredicate, authenticationOption);
            }

            var context = CrmConfigurationManager.CreateContext(ContextName);

            // NOTE: At the time this was implemented, the CrmQueryProvider was unable to handle the line below.
            // return context.CreateQuery(_profileEntityName).Count(wherePredicate);

            return(context.CreateQuery(_profileEntityName).Where(wherePredicate).ToList().Count());
        }
예제 #24
0
        public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, SettingsPropertyCollection propertyCollection)
        {
            var valueCollection = new SettingsPropertyValueCollection();

            if (propertyCollection.Count < 1)
            {
                return(valueCollection);
            }

            var username = context["UserName"] as string;

            var xrm = CrmConfigurationManager.CreateContext(ContextName);

            var entity = GetProfileEntity(xrm, username);

            foreach (SettingsProperty property in propertyCollection)
            {
                // NOTE: We just map directly to CRM proerties and ignore the serialization/deserialization capabilities of an individual SettingsPropertyValue.
                property.SerializeAs = SettingsSerializeAs.String;

                var logicalName = GetCustomProviderData(property);

                var value = entity == null ? null : entity.GetAttributeValue(logicalName);

                var settingsPropertyValue = new SettingsPropertyValue(property);

                if (value != null)
                {
                    settingsPropertyValue.Deserialized  = true;
                    settingsPropertyValue.IsDirty       = false;
                    settingsPropertyValue.PropertyValue = value;
                }

                valueCollection.Add(settingsPropertyValue);
            }

            if (_enableActivityTracking && entity != null)
            {
                entity.SetAttributeValue(_attributeMapLastActivityDate, DateTime.UtcNow);

                xrm.UpdateObject(entity);

                xrm.SaveChanges();
            }

            return(valueCollection);
        }
예제 #25
0
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            if (Items.Count > 0)
            {
                return;
            }

            var empty = new ListItem(string.Empty, string.Empty);

            empty.Attributes["label"] = " ";
            Items.Add(empty);

            var context = CrmConfigurationManager.CreateContext(ContextName);

            if (LanguageCode == 0)
            {
                var organization = context.CreateQuery("organization").FirstOrDefault();

                if (organization == null)
                {
                    ADXTrace.Instance.TraceError(TraceCategory.Application, "Failed to retrieve organization.");
                }
                else
                {
                    LanguageCode = organization.GetAttributeValue <int?>("languagecode") ?? 0;
                }
            }

            if (LanguageCode == 0)
            {
                LanguageCode = 1033;
            }

            var request = new GetAllTimeZonesWithDisplayNameRequest {
                LocaleId = LanguageCode
            };

            var response = (GetAllTimeZonesWithDisplayNameResponse)context.Execute(request);

            foreach (var timeZoneDefinition in response.EntityCollection.Entities.OrderBy(o => o.GetAttributeValue <string>("userinterfacename")))
            {
                Items.Add(new ListItem(timeZoneDefinition.GetAttributeValue <string>("userinterfacename"), timeZoneDefinition.GetAttributeValue <int>("timezonecode").ToString(CultureInfo.InvariantCulture)));
            }
        }
        protected virtual List <TimeTagItem> GetTimeTagNameSuggestions(int max)
        {
            var context = CrmConfigurationManager.CreateContext(ContextName);

            var timeTags = context.CreateQuery("adx_psa_timetag").Where(t => t.GetAttributeValue <bool>("adx_system")).OrderBy(t => t.GetAttributeValue <string>("adx_name")).Take(max);

            var tagsList = new List <TimeTagItem>();

            foreach (var tag in timeTags)
            {
                tagsList.Add(new TimeTagItem {
                    Id = tag.GetAttributeValue <Guid>("adx_psa_timetagid").ToString(), Name = tag.GetAttributeValue <string>("adx_name")
                });
            }

            return(tagsList);
        }
        protected virtual List <TimeTagItem> GetTimeTagNameCompletions(string tagNamePrefix, int max)
        {
            var context = CrmConfigurationManager.CreateContext(ContextName);

            var timeTags = context.CreateQuery("adx_psa_timetag").Where(t => t.GetAttributeValue <string>("adx_name").StartsWith(tagNamePrefix, StringComparison.InvariantCultureIgnoreCase)).OrderBy(t => t.GetAttributeValue <string>("adx_name")).Take(max);

            var tagsList = new List <TimeTagItem>();

            foreach (var tag in timeTags)
            {
                tagsList.Add(new TimeTagItem {
                    Id = tag.GetAttributeValue <Guid>("adx_psa_timetagid").ToString(), Name = tag.GetAttributeValue <string>("adx_name")
                });
            }

            return(tagsList);
        }
예제 #28
0
        /// <summary>
        /// Initializes custom settings.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="config"></param>
        public virtual void Initialize(string name, NameValueCollection config)
        {
            _name = name;

            if (config != null && Cache == null)
            {
                var innerTypeName = config["innerType"];

                if (!string.IsNullOrWhiteSpace(innerTypeName))
                {
                    // instantiate by type

                    var innerType = TypeExtensions.GetType(innerTypeName);

                    if (innerType == typeof(MemoryCache))
                    {
                        Cache = new MemoryCache(name, config);
                    }
                    else if (innerType.IsA <MemoryCache>())
                    {
                        Cache = Activator.CreateInstance(innerType, name, config) as ObjectCache;
                    }
                    else
                    {
                        Cache = Activator.CreateInstance(innerType) as ObjectCache;
                    }
                }

                var innerObjectCacheName = config["innerObjectCacheName"];

                if (!string.IsNullOrWhiteSpace(innerObjectCacheName))
                {
                    // instantiate by config

                    Cache = CrmConfigurationManager.CreateObjectCache(innerObjectCacheName);
                }
            }

            if (Cache == null)
            {
                // fall back to MemoryCache

                Cache = new MemoryCache(name, config);
            }
        }
예제 #29
0
        private static ExtendedAttributeSearchResultInfo GetExtendedAttributeInfo(string dataContextName, string logicalName, IDictionary <string, ExtendedAttributeSearchResultInfo> cache, IDictionary <string, EntityMetadata> metadataCache)
        {
            ExtendedAttributeSearchResultInfo info;

            if (cache.TryGetValue(logicalName, out info))
            {
                return(info);
            }

            var context = string.IsNullOrEmpty(dataContextName) ? CrmConfigurationManager.CreateContext() : CrmConfigurationManager.CreateContext(dataContextName);

            context.MergeOption = MergeOption.NoTracking;

            info = new ExtendedAttributeSearchResultInfo(context, logicalName, metadataCache);

            cache[logicalName] = info;

            return(info);
        }
        private static ObjectCacheProvider CreateProvider()
        {
            var section = CrmConfigurationManager.GetCrmSection();

            if (!string.IsNullOrWhiteSpace(section.ObjectCacheProviderType))
            {
                var typeName = section.ObjectCacheProviderType;
                var type     = TypeExtensions.GetType(typeName);

                if (type == null || !type.IsA <ObjectCacheProvider>())
                {
                    throw new ConfigurationErrorsException("The value '{0}' is not recognized as a valid type or is not of the type '{1}'.".FormatWith(typeName, typeof(ObjectCacheProvider)));
                }

                return(Activator.CreateInstance(type) as ObjectCacheProvider);
            }

            return(new ObjectCacheProvider());
        }