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);
            }
        }
コード例 #2
0
        public static CrmOrganizationServiceContext Create(string name = null)
        {
            var context = CrmConfigurationManager.CreateContext(name);

            context.MergeOption = MergeOption.NoTracking;

            return(context as CrmOrganizationServiceContext);
        }
コード例 #3
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();
                    }
                };
            }
        }
        /// <summary>
        /// Retrieves the configured <see cref="OrganizationServiceContext"/>.
        /// </summary>
        /// <param name="portalName"></param>
        /// <param name="allowDefaultFallback"></param>
        /// <returns></returns>
        public virtual OrganizationServiceContext CreateServiceContext(string portalName = null, bool allowDefaultFallback = false)
        {
            var portalContextElement = GetPortalContextElement(portalName, allowDefaultFallback);

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

            var context = CrmConfigurationManager.CreateContext(contextName, true);

            return(context);
        }
コード例 #6
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);
        }
コード例 #7
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());
        }
コード例 #8
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);
        }
コード例 #9
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> 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);
        }
        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);
        }
コード例 #12
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);
        }
コード例 #13
0
        public SurveyReporter(Guid surveyID)
        {
            var crm = CrmConfigurationManager.CreateContext(ContextName);

            var site = PortalContext.Current.Website;

            _survey = crm.CreateQuery("adx_survey").Where(
                survey =>
                survey.GetAttributeValue <Guid?>("adx_websiteid") == site.GetAttributeValue <Guid?>("adx_websiteid")).
                      Where(survey => survey.GetAttributeValue <Guid?>("adx_surveyid") == surveyID).First();

            _surveyChoiceQuestions = _survey.GetRelatedEntities(crm, "adx_survey_choicequestion");
            _surveyTextQuestions   = _survey.GetRelatedEntities(crm, "adx_survey_textareaquestion");
            var subs = _survey.GetRelatedEntities(crm, "adx_survey_surveysubmission");

            if (subs != null)
            {
                _surveySubmissions = subs.ToList();
            }

            if (_surveyChoiceQuestions == null && _surveyTextQuestions == null)
            {
                throw new ApplicationException("Survey Contains no questions.");
            }

            _surveyContacts          = new Entity[_surveySubmissions.Count];
            _submissionTextAnswers   = new IEnumerable <Entity> [_surveySubmissions.Count];
            _submissionChoiceAnswers = new IEnumerable <Entity> [_surveySubmissions.Count];
            //int index = 0;
            for (int index = 0; index < _surveySubmissions.Count; index++)
            {
                //_surveyContacts.Add(new CrmEntity());
                var contact = _surveySubmissions[index].GetRelatedEntity(crm, "adx_contact_surveysubmission");
                _surveyContacts[index] = contact;

                var thisSubmissionTextAnswers   = _surveySubmissions[index].GetRelatedEntities(crm, "adx_surveysubmission_surveytextanswer");
                var thisSubmissionChoiceAnswers = _surveySubmissions[index].GetRelatedEntities(crm, "adx_surveysubmission_choiceanswer");

                _submissionTextAnswers[index]   = thisSubmissionTextAnswers;
                _submissionChoiceAnswers[index] = thisSubmissionChoiceAnswers;
            }
        }
コード例 #14
0
        private ProfileInfoCollection GetProfiles(Expression <Func <Entity, bool> > wherePredicate, ProfileAuthenticationOption authenticationOption, int pageIndex, int pageSize, out int totalRecords)
        {
            var profileInfoCollection = new ProfileInfoCollection();

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

            var context = CrmConfigurationManager.CreateContext(ContextName);

            var entities = context.CreateQuery(_profileEntityName)
                           .Where(wherePredicate)
                           .OrderBy(entity => entity.GetAttributeValue <string>(_attributeMapUsername))
                           .Skip(pageIndex * pageSize)
                           .Take(pageSize);

            foreach (var entity in entities)
            {
                var username = entity.GetAttributeValue <string>(_attributeMapUsername);

                if (string.IsNullOrEmpty(username))
                {
                    continue;
                }

                profileInfoCollection.Add(
                    new ProfileInfo(
                        username,
                        entity.GetAttributeValue <bool?>(_attributeMapIsAnonymous).GetValueOrDefault(),
                        entity.GetAttributeValue <DateTime?>(_attributeMapLastActivityDate).GetValueOrDefault(),
                        entity.GetAttributeValue <DateTime?>(_attributeMapLastUpdatedDate).GetValueOrDefault(),
                        -1)
                    );
            }

            totalRecords = context.CreateQuery(_profileEntityName).Where(wherePredicate).ToList().Count();

            return(profileInfoCollection);
        }
コード例 #15
0
        override protected void OnLoad(EventArgs e)
        {
            base.OnLoad(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);
            var request            = new RetrieveProvisionedLanguagesRequest();
            var response           = (RetrieveProvisionedLanguagesResponse)context.Execute(request);
            var currentCultureInfo = System.Threading.Thread.CurrentThread.CurrentUICulture;

            if (LanguageCode > 0)
            {
                // Set the culture for the specified Language Code so the list of languages is displayed in the appropriate language.
                var tempCultureInfo = new CultureInfo(LanguageCode);
                System.Threading.Thread.CurrentThread.CurrentCulture   = tempCultureInfo;
                System.Threading.Thread.CurrentThread.CurrentUICulture = tempCultureInfo;
            }
            foreach (var lcid in response.RetrieveProvisionedLanguages)
            {
                var culture = CultureInfo.GetCultureInfo(lcid);
                Items.Add(new ListItem(culture.DisplayName, culture.LCID.ToString(CultureInfo.InvariantCulture)));
            }
            if (LanguageCode > 0)
            {
                // Reset the culture back to the original culture.
                System.Threading.Thread.CurrentThread.CurrentCulture   = currentCultureInfo;
                System.Threading.Thread.CurrentThread.CurrentUICulture = currentCultureInfo;
            }
        }
コード例 #16
0
        private void ProcessNotification(CancellationToken cancellationToken, PluginMessageRequest request)
        {
            try
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    return;
                }

                if (!WebNotificationCryptography.ValidateRequest(request.Authorization))
                {
                    WebNotificationEventSource.Log.AuthorizationValidationFailed();

                    return;
                }

                var message = this.GetMessage(request);

                if (message == null)
                {
                    WebNotificationEventSource.Log.MessageInvalid();

                    return;
                }

                CacheInvalidation.ProcessMessage(message);

                if (SearchIndexApplicableMessages.Contains(message.MessageName, MessageComparer))
                {
                    var serviceContext = CrmConfigurationManager.CreateContext();
                    SearchIndexBuildRequest.ProcessMessage(message, serviceContext: serviceContext);
                }
            }
            catch (TaskCanceledException e)
            {
                ADXTrace.Instance.TraceWarning(TraceCategory.Application, e.Message);
            }
        }
コード例 #17
0
        public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection)
        {
            var username = context["UserName"] as string;

            var xrm = CrmConfigurationManager.CreateContext(ContextName);

            var entity = GetProfileEntity(xrm, username);

            if (collection.Count < 1 || string.IsNullOrEmpty(username) || entity == null)
            {
                return;
            }

            var userIsAuthenticated = (context["IsAuthenticated"] as bool?).GetValueOrDefault();

            if (!userIsAuthenticated && collection.Cast <SettingsPropertyValue>().Any(propertyValue => (propertyValue.Property.Attributes["AllowAnonymous"] as bool?).GetValueOrDefault()))
            {
                throw new NotSupportedException("Anonymous properties aren't supported.");
            }

            var propertyValuesToUpdate = collection.Cast <SettingsPropertyValue>().Where(value => value.IsDirty && !value.UsingDefaultValue);

            foreach (var propertyValue in propertyValuesToUpdate)
            {
                var logicalName = GetCustomProviderData(propertyValue.Property);

                entity.SetAttributeValue(logicalName, propertyValue.PropertyValue);
            }

            entity.SetAttributeValue(_attributeMapLastActivityDate, DateTime.UtcNow);

            entity.SetAttributeValue(_attributeMapLastUpdatedDate, DateTime.UtcNow);

            xrm.UpdateObject(entity);

            xrm.SaveChanges();
        }
コード例 #18
0
        protected override void InstantiateControlIn(Control container)
        {
            var textbox = new TextBox {
                ID = ControlID, TextMode = TextBoxMode.SingleLine, CssClass = string.Join(" ", "text", CssClass, Metadata.CssClass), ToolTip = Metadata.ToolTip
            };

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

            if (Metadata.ReadOnly)
            {
                textbox.CssClass += " readonly";
                textbox.Attributes["readonly"] = "readonly";
            }

            textbox.Attributes["onchange"] = "setIsDirty(this.id);";

            var inputGroup           = new HtmlGenericControl("div");
            var inputGroupAddonFirst = new HtmlGenericControl("span")
            {
                Visible = false
            };
            var inputGroupAddonLast = new HtmlGenericControl("span")
            {
                Visible = false
            };

            inputGroupAddonFirst.Attributes["class"] = "input-group-addon";
            inputGroupAddonLast.Attributes["class"]  = "input-group-addon";

            inputGroup.Controls.Add(inputGroupAddonFirst);
            inputGroup.Controls.Add(textbox);
            inputGroup.Controls.Add(inputGroupAddonLast);

            container.Controls.Add(inputGroup);

            RegisterClientSideDependencies(container);

            Bindings[Metadata.DataFieldName] = new CellBinding
            {
                Get = () =>
                {
                    decimal value;

                    return(decimal.TryParse(textbox.Text, out value) ? new decimal?(value) : null);
                },
                Set = obj =>
                {
                    var data = obj as Tuple <Entity, Money>;

                    if (data == null)
                    {
                        textbox.Text = ((Money)obj).Value.ToString("N{0}".FormatWith(Metadata.Precision));

                        return;
                    }

                    using (var serviceContext = CrmConfigurationManager.CreateContext(ContextName))
                    {
                        var moneyFormatter = new MoneyFormatter(
                            new OrganizationMoneyFormatInfo(serviceContext),
                            new EntityRecordMoneyFormatInfo(serviceContext, data.Item1),
                            Metadata.Precision,
                            Metadata.PrecisionSource,
                            Metadata.IsBaseCurrency);

                        // Include the currency symbol in the field value if it's read-only (for nicer display, as
                        // it won't need to be parsed later.
                        textbox.Text = string.Format(moneyFormatter, Metadata.ReadOnly ? "{0}" : "{0:N}", data.Item2);

                        if (!(Metadata.ReadOnly || string.IsNullOrEmpty(moneyFormatter.CurrencySymbol)))
                        {
                            inputGroup.Attributes["class"] = "input-group";

                            var addon = moneyFormatter.CurrencySymbolComesFirst
                                                                ? inputGroupAddonFirst
                                                                : inputGroupAddonLast;

                            addon.InnerText = moneyFormatter.CurrencySymbol;
                            addon.Visible   = true;
                        }
                    }
                }
            };
        }
コード例 #19
0
        private void PopulateDropDown(DropDownList dropDown)
        {
            if (dropDown.Items.Count > 0)
            {
                return;
            }

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

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

            var context = CrmConfigurationManager.CreateContext();

            var service = CrmConfigurationManager.CreateService();

            // By default a lookup field cell defined in the form XML does not contain view parameters unless the user has specified a view that is not the default for that entity and we must query to find the default view.  Saved Query entity's QueryType code 64 indicates a lookup view.

            var view = Metadata.LookupViewID == Guid.Empty ? context.CreateQuery("savedquery").FirstOrDefault(s => s.GetAttributeValue <string>("returnedtypecode") == "subject" && s.GetAttributeValue <bool?>("isdefault").GetValueOrDefault(false) && s.GetAttributeValue <int>("querytype") == 64) : context.CreateQuery("savedquery").FirstOrDefault(s => s.GetAttributeValue <Guid>("savedqueryid") == Metadata.LookupViewID);

            List <Entity> subjects;

            if (view != null)
            {
                var fetchXML = view.GetAttributeValue <string>("fetchxml");

                var xElement = XElement.Parse(fetchXML);

                var parentsubjectElement = xElement.Descendants("attribute").FirstOrDefault(e =>
                {
                    var xAttribute = e.Attribute("name");
                    return(xAttribute != null && xAttribute.Value == "parentsubject");
                });

                if (parentsubjectElement == null)
                {
                    //If fetchxml does not contain the parentsubject attribute then it must be injected so the results can be organized in a hierarchical order.

                    var entityElement = xElement.Element("entity");

                    if (entityElement == null)
                    {
                        return;
                    }

                    var p = new XElement("attribute", new XAttribute("name", "parentsubject"));

                    entityElement.Add(p);

                    fetchXML = xElement.ToString();
                }

                var data = service.RetrieveMultiple(new FetchExpression(fetchXML));

                if (data == null || data.Entities == null)
                {
                    return;
                }

                subjects = data.Entities.ToList();
            }
            else
            {
                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;
                }

                dropDown.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(dropDown, subjects, children, 1);
            }
        }
コード例 #20
0
        /// <summary>
        /// Control instantiation
        /// </summary>
        /// <param name="container"></param>
        protected override void InstantiateControlIn(HtmlControl container)
        {
            if (string.IsNullOrWhiteSpace(Metadata.ViewID))
            {
                return;
            }

            var context = CrmConfigurationManager.CreateContext(ContextName);
            var portal  = PortalCrmConfigurationManager.CreatePortalContext(ContextName);
            var user    = portal == null ? null : portal.User;

            EntityMetadata = GetEntityMetadata(context);

            var viewId = new Guid(Metadata.ViewID);

            if (viewId == Guid.Empty)
            {
                return;
            }

            var viewGuids = new[] { viewId };

            if (Metadata.ViewEnableViewPicker && !string.IsNullOrWhiteSpace(Metadata.ViewIds))
            {
                var viewids = Metadata.ViewIds.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                if (viewids.Length >= 1)
                {
                    viewGuids = Array.ConvertAll(viewids, Guid.Parse).AsEnumerable().OrderBy(o => o != viewId).ThenBy(o => o).ToArray();
                }
            }

            Bindings[Metadata.ControlID + "CrmEntityId"] = new CellBinding
            {
                Get = () => null,
                Set = obj =>
                {
                    var  id = obj.ToString();
                    Guid entityId;

                    if (!Guid.TryParse(id, out entityId))
                    {
                        return;
                    }

                    var subgridHtml = BuildGrid(container, context, viewGuids, viewId, entityId, user);
                    var subgrid     = new HtmlGenericControl("div")
                    {
                        ID = Metadata.ControlID, InnerHtml = subgridHtml.ToString()
                    };
                    subgrid.Attributes.Add("class", "subgrid");
                    container.Controls.Add(subgrid);
                }
            };

            if (!container.Page.IsPostBack)
            {
                return;
            }

            // On PostBack no databinding occurs so get the id from the viewstate stored on the CrmEntityFormView control.
            var crmEntityId = Metadata.FormView.CrmEntityId;

            if (crmEntityId == null)
            {
                return;
            }

            var gridHtml       = BuildGrid(container, context, viewGuids, viewId, (Guid)crmEntityId, user);
            var subgridControl = new HtmlGenericControl("div")
            {
                ID = Metadata.ControlID, InnerHtml = gridHtml.ToString()
            };

            subgridControl.Attributes.Add("class", "subgrid");
            container.Controls.Add(subgridControl);
        }
コード例 #21
0
        /// <summary>
        /// Generate the HTML to render a modal lookup records dialog.
        /// </summary>
        protected virtual IHtmlString BuildLookupModal(Control container)
        {
            var html                           = Mvc.Html.EntityExtensions.GetHtmlHelper(Metadata.FormView.ContextName, container.Page.Request.RequestContext, container.Page.Response); //new HtmlHelper(new ViewContext(), new ViewPage());
            var context                        = CrmConfigurationManager.CreateContext(Metadata.FormView.ContextName);
            var portal                         = PortalCrmConfigurationManager.CreatePortalContext(Metadata.FormView.ContextName);
            var user                           = portal == null ? null : portal.User;
            var viewConfigurations             = new List <ViewConfiguration>();
            var defaultViewId                  = Metadata.LookupViewID;
            var modalGridSearchPlaceholderText = html.SnippetLiteral("Portal/Lookup/Modal/Grid/Search/PlaceholderText");
            var modalGridSearchTooltipText     = html.SnippetLiteral("Portal/Lookup/Modal/Grid/Search/TooltipText");
            var modalGridPageSize              = html.IntegerSetting("Portal/Lookup/Modal/Grid/PageSize") ?? 10;
            var modalSizeSetting               = html.Setting("Portal/Lookup/Modal/Size");
            var modalSize                      = BootstrapExtensions.BootstrapModalSize.Large;

            if (modalSizeSetting != null && modalSizeSetting.ToLower() == "default")
            {
                modalSize = BootstrapExtensions.BootstrapModalSize.Default;
            }
            if (modalSizeSetting != null && modalSizeSetting.ToLower() == "small")
            {
                modalSize = BootstrapExtensions.BootstrapModalSize.Small;
            }

            var formEntityReferenceInfo = GetFormEntityReferenceInfo(container.Page.Request);

            if (defaultViewId == Guid.Empty)
            {
                // By default a lookup field cell defined in the form XML does not contain view parameters unless the user has specified a view that is not the default for that entity and we must query to find the default view.  Saved Query entity's QueryType code 64 indicates a lookup view.

                viewConfigurations.AddRange(
                    Metadata.LookupTargets.Select(
                        target => new ViewConfiguration(new SavedQueryView(context, target, 64, true, Metadata.LanguageCode), modalGridPageSize)
                {
                    Search = new ViewSearch(!Metadata.LookupDisableQuickFind)
                    {
                        PlaceholderText = modalGridSearchPlaceholderText, TooltipText = modalGridSearchTooltipText
                    },
                    EnableEntityPermissions = Metadata.FormView.EnableEntityPermissions,
                    PortalName   = Metadata.FormView.ContextName,
                    LanguageCode = Metadata.LanguageCode,
                    ModalLookupAttributeLogicalName           = Metadata.DataFieldName,
                    ModalLookupEntityLogicalName              = Metadata.TargetEntityName,
                    ModalLookupFormReferenceEntityId          = formEntityReferenceInfo.Item2,
                    ModalLookupFormReferenceEntityLogicalName = formEntityReferenceInfo.Item1,
                    ModalLookupFormReferenceRelationshipName  = formEntityReferenceInfo.Item3,
                    ModalLookupFormReferenceRelationshipRole  = formEntityReferenceInfo.Item4
                }));
            }
            else
            {
                viewConfigurations.Add(new ViewConfiguration(new SavedQueryView(context, defaultViewId, Metadata.LanguageCode), modalGridPageSize)
                {
                    Search = new ViewSearch(!Metadata.LookupDisableQuickFind)
                    {
                        PlaceholderText = modalGridSearchPlaceholderText, TooltipText = modalGridSearchTooltipText
                    },
                    EnableEntityPermissions = Metadata.FormView.EnableEntityPermissions,
                    PortalName   = Metadata.FormView.ContextName,
                    LanguageCode = Metadata.LanguageCode,
                    ModalLookupAttributeLogicalName           = Metadata.DataFieldName,
                    ModalLookupEntityLogicalName              = Metadata.TargetEntityName,
                    ModalLookupFormReferenceEntityId          = formEntityReferenceInfo.Item2,
                    ModalLookupFormReferenceEntityLogicalName = formEntityReferenceInfo.Item1,
                    ModalLookupFormReferenceRelationshipName  = formEntityReferenceInfo.Item3,
                    ModalLookupFormReferenceRelationshipRole  = formEntityReferenceInfo.Item4
                });
            }

            if (!Metadata.LookupDisableViewPicker && !string.IsNullOrWhiteSpace(Metadata.LookupAvailableViewIds))
            {
                var addViewConfigurations = new List <ViewConfiguration>();
                var viewids = Metadata.LookupAvailableViewIds.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                if (viewids.Length >= 1)
                {
                    var viewGuids = Array.ConvertAll(viewids, Guid.Parse).AsEnumerable().OrderBy(o => o != defaultViewId).ThenBy(o => o).ToArray();
                    addViewConfigurations.AddRange(from viewGuid in viewGuids
                                                   from viewConfiguration in viewConfigurations
                                                   where viewConfiguration.ViewId != viewGuid
                                                   select new ViewConfiguration(new SavedQueryView(context, viewGuid, Metadata.LanguageCode), modalGridPageSize)
                    {
                        Search = new ViewSearch(!Metadata.LookupDisableQuickFind)
                        {
                            PlaceholderText = modalGridSearchPlaceholderText, TooltipText = modalGridSearchTooltipText
                        },
                        EnableEntityPermissions = Metadata.FormView.EnableEntityPermissions,
                        PortalName   = Metadata.FormView.ContextName,
                        LanguageCode = Metadata.LanguageCode,
                        ModalLookupAttributeLogicalName           = Metadata.DataFieldName,
                        ModalLookupEntityLogicalName              = Metadata.TargetEntityName,
                        ModalLookupFormReferenceEntityId          = formEntityReferenceInfo.Item2,
                        ModalLookupFormReferenceEntityLogicalName = formEntityReferenceInfo.Item1,
                        ModalLookupFormReferenceRelationshipName  = formEntityReferenceInfo.Item3,
                        ModalLookupFormReferenceRelationshipRole  = formEntityReferenceInfo.Item4
                    });
                }
                viewConfigurations.AddRange(addViewConfigurations);
            }

            var    applyRelatedRecordFilter = !string.IsNullOrWhiteSpace(Metadata.LookupFilterRelationshipName);
            string filterFieldName          = null;

            if (!string.IsNullOrWhiteSpace(Metadata.LookupDependentAttributeName))             // entity.attribute (i.e. contact.adx_subject)
            {
                var pos = Metadata.LookupDependentAttributeName.IndexOf(".", StringComparison.InvariantCulture);
                filterFieldName = pos >= 0
                                        ? Metadata.LookupDependentAttributeName.Substring(pos + 1)
                                        : Metadata.LookupDependentAttributeName;
            }

            var modalTitle                   = html.SnippetLiteral("Portal/Lookup/Modal/Title");
            var modalPrimaryButtonText       = html.SnippetLiteral("Portal/Lookup/Modal/PrimaryButtonText");
            var modalCancelButtonText        = html.SnippetLiteral("Portal/Lookup/Modal/CancelButtonText");
            var modalDismissButtonSrText     = html.SnippetLiteral("Portal/Lookup/Modal/DismissButtonSrText");
            var modalRemoveValueButtonText   = html.SnippetLiteral("Portal/Lookup/Modal/RemoveValueButtonText");
            var modalNewValueButtonText      = html.SnippetLiteral("Portal/Lookup/Modal/NewValueButtonText");
            var modalDefaultErrorMessage     = html.SnippetLiteral("Portal/Lookup/Modal/DefaultErrorMessage");
            var modalGridLoadingMessage      = html.SnippetLiteral("Portal/Lookup/Modal/Grid/LoadingMessage");
            var modalGridErrorMessage        = html.SnippetLiteral("Portal/Lookup/Modal/Grid/ErrorMessage");
            var modalGridAccessDeniedMessage = html.SnippetLiteral("Portal/Lookup/Modal/Grid/AccessDeniedMessage");
            var modalGridEmptyMessage        = html.SnippetLiteral("Portal/Lookup/Modal/Grid/EmptyMessage");
            var modalGridToggleFilterText    = html.SnippetLiteral("Portal/Lookup/Modal/Grid/ToggleFilterText");

            return(html.LookupModal(ControlID, viewConfigurations,
                                    BuildControllerActionUrl("GetLookupGridData", "EntityGrid", new { area = "Portal", __portalScopeId__ = portal == null ? Guid.Empty : portal.Website.Id }), user, applyRelatedRecordFilter,
                                    Metadata.LookupAllowFilterOff, Metadata.LookupFilterRelationshipName, Metadata.LookupDependentAttributeType,
                                    filterFieldName, null, null, modalTitle, modalPrimaryButtonText, modalCancelButtonText, modalDismissButtonSrText,
                                    modalRemoveValueButtonText, modalNewValueButtonText, null, null, modalGridLoadingMessage, modalGridErrorMessage, modalGridAccessDeniedMessage,
                                    modalGridEmptyMessage, modalGridToggleFilterText, modalDefaultErrorMessage, null, null, null, Metadata.FormView.ContextName,
                                    Metadata.LanguageCode, null, modalSize, Metadata.LookupReferenceEntityFormId, EvaluateCreatePrivilege(portal.ServiceContext),
                                    ControlID == "entitlementid" ? BuildControllerActionUrl("GetDefaultEntitlements", "Entitlements", new { area = "CaseManagement", __portalScopeId__ = portal == null ? Guid.Empty : portal.Website.Id }) : null));
        }
コード例 #22
0
        public void Write(HtmlTextWriter writer)
        {
            writer.RenderBeginTag(HtmlTextWriterTag.Table);

            writer.RenderBeginTag(HtmlTextWriterTag.Tr);

            writer.RenderBeginTag(HtmlTextWriterTag.Th);
            writer.Write("Submission name");
            writer.RenderEndTag();

            writer.RenderBeginTag(HtmlTextWriterTag.Th);
            writer.Write("Visitor ID");
            writer.RenderEndTag();

            writer.RenderBeginTag(HtmlTextWriterTag.Th);
            writer.Write("Contact Name");
            writer.RenderEndTag();

            foreach (var question in _surveyChoiceQuestions)
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Th);
                writer.Write(question.GetAttributeValue <string>("adx_name"));
                writer.RenderEndTag();

                writer.RenderBeginTag(HtmlTextWriterTag.Th);
                writer.Write(question.GetAttributeValue <string>("adx_question"));
                writer.RenderEndTag();
            }

            foreach (var question in _surveyTextQuestions)
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Th);
                writer.Write(question.GetAttributeValue <string>("adx_name") + " : " + question.GetAttributeValue <string>("adx_question"));
                writer.RenderEndTag();
            }

            writer.RenderEndTag();

            if (_surveySubmissions == null)
            {
                writer.RenderEndTag();
                return;
            }


            for (int i = 0; i < _surveySubmissions.Count; i++)
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Tr);
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                writer.Write(_surveySubmissions[i].GetAttributeValue <string>("adx_name"));
                writer.RenderEndTag();

                var contact = _surveyContacts[i];

                if (contact != null)
                {
                    writer.RenderBeginTag(HtmlTextWriterTag.Td);
                    writer.Write(@"&nbsp;");
                    writer.RenderEndTag();
                    writer.RenderBeginTag(HtmlTextWriterTag.Td);
                    writer.Write(contact.GetAttributeValue <string>("fullname"));
                    writer.RenderEndTag();
                }
                else
                {
                    writer.RenderBeginTag(HtmlTextWriterTag.Td);
                    writer.Write(_surveySubmissions[i].GetAttributeValue <string>("adx_visitorid"));
                    writer.RenderEndTag();
                    writer.RenderBeginTag(HtmlTextWriterTag.Td);
                    writer.Write(@"&nbsp;");
                    writer.RenderEndTag();
                }

                var thisSubmissionTextAnswers   = _submissionTextAnswers[i];
                var thisSubmissionChoiceAnswers = _submissionChoiceAnswers[i];

                var crm = CrmConfigurationManager.CreateContext(ContextName);

                foreach (var question in _surveyChoiceQuestions)
                {
                    bool answered = false;
                    foreach (var answer in thisSubmissionChoiceAnswers)
                    {
                        var    anses   = crm.CreateQuery("adx_surveychoiceanswer");
                        Entity answer1 = answer;
                        var    ans     = anses.Where(a => a.GetAttributeValue <Guid>("adx_surveychoiceanswerid") == answer1.GetAttributeValue <Guid>("adx_surveychoiceanswerid")).First();
                        if (ans.GetRelatedEntity(crm, "adx_choicequestion_choiceanswer").GetAttributeValue <Guid?>("adx_surveychoicequestionid")
                            == question.GetAttributeValue <Guid?>("adx_surveychoicequestionid"))
                        {
                            string partialChoiceList = "";
                            var    choices           = ans.GetRelatedEntities(crm, "adx_surveychoiceanswer_surveychoice");
                            foreach (var entity in choices)
                            {
                                partialChoiceList = partialChoiceList + entity.GetAttributeValue <string>("adx_name") + "|";
                            }
                            string pattern     = @"\|$";
                            string replacement = " ";

                            writer.RenderBeginTag(HtmlTextWriterTag.Td);

                            if (partialChoiceList != null)
                            {
                                string result = Regex.Replace(partialChoiceList, pattern, replacement);
                                writer.Write(result);
                            }
                            else
                            {
                                writer.Write(partialChoiceList);
                            }
                            writer.RenderEndTag();

                            writer.RenderBeginTag(HtmlTextWriterTag.Td);

                            string input = ans.GetAttributeValue <string>("adx_answer");

                            if (input != null)
                            {
                                string result = Regex.Replace(input, pattern, replacement);
                                writer.Write(result);
                            }
                            else
                            {
                                writer.Write(input);
                            }
                            writer.RenderEndTag();
                            answered = true;
                        }
                    }
                    if (!answered)
                    {
                        writer.RenderBeginTag(HtmlTextWriterTag.Td);
                        writer.Write(@"&nbsp;");
                        writer.RenderEndTag();
                    }
                }
                foreach (var question in _surveyTextQuestions)
                {
                    bool answered = false;
                    foreach (var answer in thisSubmissionTextAnswers)
                    {
                        var    anses   = crm.CreateQuery("adx_surveytextanswer");
                        Entity answer1 = answer;
                        var    ans     = anses.Where(a => a.GetAttributeValue <Guid>("adx_surveytextanswerid") == answer1.GetAttributeValue <Guid>("adx_surveytextanswerid")).First();
                        if (ans.GetRelatedEntity(crm, "adx_textareaquestion_textanswer").GetAttributeValue <Guid?>("adx_surveytextareaquestionid")
                            == question.GetAttributeValue <Guid?>("adx_surveytextareaquestionid"))
                        {
                            writer.RenderBeginTag(HtmlTextWriterTag.Td);
                            if (String.IsNullOrEmpty(ans.GetAttributeValue <string>("adx_answer")))
                            {
                                writer.Write(@"&nbsp;");
                            }
                            else
                            {
                                writer.Write(ans.GetAttributeValue <string>("adx_answer"));
                            }
                            //writer.Write(answer.GetAttributeValue<string>("adx_answer"));
                            writer.RenderEndTag();
                            answered = true;
                        }
                    }
                    if (!answered)
                    {
                        writer.RenderBeginTag(HtmlTextWriterTag.Td);
                        writer.Write(@"&nbsp;");
                        writer.RenderEndTag();
                    }
                }

                writer.RenderEndTag();
            }

            writer.RenderEndTag();
            writer.Flush();
        }
        protected void CreateControls(Control container, Guid entityId)
        {
            // Add a placeholder element with the control ID that will always be present, so
            // that any potential cell label will still have an control to associate with.
            var placeholder = new PlaceHolder {
                ID = Metadata.ControlID
            };

            container.Controls.Add(placeholder);

            var context   = CrmConfigurationManager.CreateContext(ContextName, true);
            var quickForm = Metadata.QuickForm.QuickFormIds.FirstOrDefault();

            if (quickForm == null)
            {
                return;
            }

            var filterExpression = new FilterExpression();

            filterExpression.Conditions.Add(new ConditionExpression("formid", ConditionOperator.Equal, quickForm.FormId));

            var systemForm = Xrm.Metadata.OrganizationServiceContextExtensions.GetMultipleSystemFormsWithAllLabels(filterExpression, context).FirstOrDefault();

            if (systemForm == null)
            {
                ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Quick Form: A form with ID='{0}' could not be found.".FormatWith(quickForm.FormId)));

                return;
            }

            var formName = systemForm.GetAttributeValue <string>("name");

            if (string.IsNullOrWhiteSpace(formName))
            {
                ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Quick Form: Form with ID='{0}' does not have a name.".FormatWith(quickForm.FormId)));

                return;
            }

            var templatePath = GetPortalQuickFormTemplatePath(ContextName);

            if (string.IsNullOrWhiteSpace(templatePath))
            {
                ADXTrace.Instance.TraceError(TraceCategory.Application, "Failed to retrieve Quick Form template path.");

                return;
            }

            var iframe = new HtmlIframe {
                ID = Metadata.ControlID, Src = "about:blank"
            };

            iframe.Attributes.Add("class", "quickform");
            iframe.Attributes.Add("data-path", templatePath);
            iframe.Attributes.Add("data-controlid", Metadata.ControlID);
            iframe.Attributes.Add("data-formname", formName);
            iframe.Attributes.Add("data-lookup-element", Metadata.DataFieldName);

            container.Controls.Remove(placeholder);
            container.Controls.Add(iframe);

            var primaryKeyAttributeName = MetadataHelper.GetEntityPrimaryKeyAttributeLogicalName(context, quickForm.EntityName);

            if (string.IsNullOrWhiteSpace(primaryKeyAttributeName))
            {
                ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Error retrieving the Primary Key Attribute Name for '{0}'.", EntityNamePrivacy.GetEntityName(quickForm.EntityName)));

                return;
            }

            if (string.IsNullOrWhiteSpace(Metadata.DataFieldName))
            {
                ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Quick Form: datafieldname is null for QuickForm with ID='{0}'", quickForm.FormId));

                return;
            }

            var formEntity = context.CreateQuery(Metadata.TargetEntityName).FirstOrDefault(e => e.GetAttributeValue <Guid>(Metadata.TargetEntityPrimaryKeyName) == entityId);

            if (formEntity == null)
            {
                ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Failed to retrieve entity record with ID='{0}'", entityId));

                return;
            }

            var quickFormEntityReference = formEntity.GetAttributeValue <EntityReference>(Metadata.DataFieldName);

            if (quickFormEntityReference == null)
            {
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Attribute on entity record with ID='{0}' is null. Quick Form not loaded.", entityId));

                return;
            }

            var src = templatePath;

            src = src.AppendQueryString("entityid", quickFormEntityReference.Id.ToString());
            src = src.AppendQueryString("entityname", quickForm.EntityName);
            src = src.AppendQueryString("entityprimarykeyname", primaryKeyAttributeName);
            src = src.AppendQueryString("formname", formName);
            src = src.AppendQueryString("controlid", Metadata.ControlID);

            iframe.Src = src;
        }
        private void PopulateDropDownIfFirstLoad(DropDownList dropDown, string lookupEntityName)
        {
            if (dropDown.Items.Count > 0)
            {
                return;
            }

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

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

            var context = CrmConfigurationManager.CreateContext();

            var service = CrmConfigurationManager.CreateService();

            var metadataCache                 = new Dictionary <string, EntityMetadata>();
            var entityMetadata                = GetEntityMetadata(context, Metadata.LookupTargets[0], metadataCache);
            var primaryNameAttribute          = entityMetadata.PrimaryNameAttribute;
            var primaryKeyAttribute           = entityMetadata.PrimaryIdAttribute;
            var localizedPrimaryNameAttribute = primaryNameAttribute;

            // get a localized primary attribute name
            if (Metadata.LanguageCode > 0)
            {
                var defaultLanguageCode = RetrieveOrganizationBaseLanguageCode(context);
                if (Metadata.LanguageCode != defaultLanguageCode)
                {
                    localizedPrimaryNameAttribute = string.Format("{0}_{1}", primaryNameAttribute, Metadata.LanguageCode);
                    foreach (var att in entityMetadata.Attributes.Where(att => att.LogicalName.EndsWith(localizedPrimaryNameAttribute)))
                    {
                        primaryNameAttribute = att.LogicalName;
                        break;
                    }
                }
            }

            // By default a lookup field cell defined in the form XML does not contain view parameters unless the user has specified a view that is not the default for that entity and we must query to find the default view.  Saved Query entity's QueryType code 64 indicates a lookup view.

            var view = Metadata.LookupViewID == Guid.Empty ? context.CreateQuery("savedquery").FirstOrDefault(s => s.GetAttributeValue <string>("returnedtypecode") == lookupEntityName && s.GetAttributeValue <bool>("isdefault") && s.GetAttributeValue <int>("querytype") == 64) : context.CreateQuery("savedquery").FirstOrDefault(s => s.GetAttributeValue <Guid>("savedqueryid") == Metadata.LookupViewID);

            IQueryable <Entity> lookupEntities;

            if (view != null)
            {
                var fetchXml = view.GetAttributeValue <string>("fetchxml");

                lookupEntities = GetLookupRecords(fetchXml, context);

                if (lookupEntities == null)
                {
                    return;
                }
            }
            else
            {
                string fetchXml = string.Format(@"
					<fetch mapping='logical'>
						<entity name='{0}'> 
							<attribute name='{1}'/>
							<attrbiute name='{2}'/>
						</entity> 
					</fetch> "                    , lookupEntityName, primaryKeyAttribute, primaryNameAttribute);

                lookupEntities = GetLookupRecords(fetchXml, context);

                if (lookupEntities == null)
                {
                    return;
                }
            }

            foreach (var entity in lookupEntities)
            {
                dropDown.Items.Add(new ListItem
                {
                    Value = entity.Id.ToString(),
                    Text  = entity.Attributes.ContainsKey(localizedPrimaryNameAttribute) ? entity.GetAttributeValue(localizedPrimaryNameAttribute).ToString() : entity.Attributes.ContainsKey(primaryNameAttribute) ? entity.GetAttributeValue(primaryNameAttribute).ToString() : string.Empty
                });
            }
        }
コード例 #25
0
 public PortalContext(string contextName, RequestContext request, IWebsiteSelector websiteSelector)
     : this(CrmConfigurationManager.CreateContext(contextName), request, websiteSelector)
 {
 }
コード例 #26
0
        /// <summary>
        /// Method to process the node of the current request and save tracking info.
        /// </summary>
        private static void LogRequest(CrmSiteMapNode node, string ipAddress, Entity user)
        {
            if (node == null)
            {
                return;
            }

            if (node.StatusCode != HttpStatusCode.OK)
            {
                return;                                                   //possbily put 404 tracking in here?
            }
            var context = CrmConfigurationManager.CreateContext();

            switch (node.Entity.LogicalName)
            {
            case "adx_webpage":

                var webpage = context.CreateQuery("adx_webpage").FirstOrDefault(w => w.GetAttributeValue <Guid>("adx_webpageid") == node.Entity.Id);

                if (webpage != null && (webpage.GetAttributeValue <bool?>("adx_enabletracking") ?? false))
                {
                    var webpagelog = new Entity("adx_webpagelog");

                    webpagelog.SetAttributeValue("adx_name", webpage.GetAttributeValue <string>("adx_name") + " log");

                    webpagelog.SetAttributeValue("adx_date", DateTime.UtcNow);

                    webpagelog.SetAttributeValue("adx_ipaddress", ipAddress);

                    context.AddObject(webpagelog);

                    context.AddLink(webpagelog, "adx_webpage_webpagelog".ToRelationship(), webpage);

                    if (user != null)
                    {
                        var contact = context.CreateQuery("contact").FirstOrDefault(c => c.GetAttributeValue <Guid>("contactid") == user.Id);

                        if (contact != null)
                        {
                            context.AddLink(webpagelog, "adx_contact_webpagelog".ToRelationship(), contact);
                        }
                    }

                    context.SaveChanges();
                }

                break;

            case "adx_webfile":

                var webfile = context.CreateQuery("adx_webfile").FirstOrDefault(w => w.GetAttributeValue <Guid>("adx_webfileid") == node.Entity.Id);

                if (webfile != null && (webfile.GetAttributeValue <bool?>("adx_enabletracking") ?? false))
                {
                    var webfilelog = new Entity("adx_webfilelog");

                    webfilelog.SetAttributeValue("adx_name", webfile.GetAttributeValue <string>("adx_name") + " log");

                    webfilelog.SetAttributeValue("adx_date", DateTime.UtcNow);

                    webfilelog.SetAttributeValue("adx_ipaddress", ipAddress);

                    context.AddObject(webfilelog);

                    context.AddLink(webfilelog, "adx_webfile_webfilelog".ToRelationship(), webfile);

                    if (user != null)
                    {
                        var contact = context.CreateQuery("contact").FirstOrDefault(c => c.GetAttributeValue <Guid>("contactid") == user.Id);

                        if (contact != null)
                        {
                            context.AddLink(webfilelog, "adx_contact_webfilelog".ToRelationship(), contact);
                        }
                    }

                    context.SaveChanges();
                }

                break;
            }
        }