public override void Init(System.Html.Element element, Func<object> valueAccessor, Func<System.Collections.Dictionary> allBindingsAccessor, object viewModel, object context)
        {
            // Get the text box element
            jQueryObject select = jQuery.FromElement(element).Find(".sparkle-input-optionset-part");

            jQueryEventHandler onChangeHandler = delegate(jQueryEvent e)
            {
                Observable<OptionSetValue> observable = (Observable<OptionSetValue>)valueAccessor();
                string newValue = select.GetValue();
                int? newValueInt = null;
                if (!String.IsNullOrEmpty(newValue))
                {
                    newValueInt = int.Parse(newValue);
                }
                // Set the optionset value
                OptionSetValue newValueOptionSetValue = new OptionSetValue(newValueInt);
                newValueOptionSetValue.Name = select.Find("option:selected").GetText();
                observable.SetValue(newValueOptionSetValue);
            };

            select.Change(onChangeHandler);

            allBindingsAccessor()["optionsValue"] = "value";
            allBindingsAccessor()["optionsText"] = "name";

            OptionSetBindingOptions optionSetOptions = (OptionSetBindingOptions)((object)allBindingsAccessor()["optionSetOptions"]);
            // Create a value accessor for the optionset options
            Func<List<OptionSetItem>> optionsValueAccessor = delegate() {
                return  MetadataCache.GetOptionSetValues(optionSetOptions.entityLogicalName, optionSetOptions.attributeLogicalName,optionSetOptions.allowEmpty);
            };

            Script.Literal("ko.bindingHandlers.options.update({0},{1},{2},{3},{4})", select.GetElement(0), optionsValueAccessor, allBindingsAccessor, viewModel, context);

            //Script.Literal("return { controlsDescendantBindings: true };");
        }
Ejemplo n.º 2
0
        public static object DeSerialise(XmlNode node, string overrideType)
        {
            // Check if the value is null
            bool   isNil = (XmlHelper.GetAttributeValue(node, "i:nil") == "true");
            object value = null;

            if (!isNil)
            {
                string typeName = overrideType;
                if (typeName == null)
                {
                    typeName = _removeNsPrefix(XmlHelper.GetAttributeValue(node, "i:type"));
                }

                string stringValue = XmlHelper.GetNodeTextValue(node);
                switch (typeName)
                {
                case AttributeTypes.EntityReference:
                    EntityReference entityReferenceValue = new EntityReference(
                        new Guid(XmlHelper.SelectSingleNodeValue(node, "Id")),
                        XmlHelper.SelectSingleNodeValue(node, "LogicalName"),
                        XmlHelper.SelectSingleNodeValue(node, "Name"));

                    value = entityReferenceValue;
                    break;

                case AttributeTypes.AliasedValue:
                    value = DeSerialise(XmlHelper.SelectSingleNode(node, "Value"), null);
                    break;

                case AttributeTypes.Boolean_:
                    value = (stringValue == "true");
                    break;

                case AttributeTypes.Decimal_:
                    value = decimal.Parse(stringValue);
                    break;

                case AttributeTypes.DateTime_:
                    DateTime dateValue = DateTimeEx.Parse(stringValue);

                    // We need it in the CRM Users timezone
                    UserSettings settings = OrganizationServiceProxy.UserSettings;
                    if (settings != null)
                    {
                        // Remove the local date formating so that it is in UTC irrespective of the local timezone
                        dateValue.SetTime(dateValue.GetTime() + (dateValue.GetTimezoneOffset() * 60 * 1000));

                        DateTime localDateValue = DateTimeEx.UTCToLocalTimeFromSettings(dateValue, settings);
                        value = localDateValue;
                    }
                    else
                    {
                        value = dateValue;
                    }

                    break;

                case "guid":
                    value = new Guid(stringValue);
                    break;

                case AttributeTypes.Int_:
                    value = int.Parse(stringValue);
                    break;

                case AttributeTypes.OptionSetValue:
                    value = OptionSetValue.Parse(XmlHelper.SelectSingleNodeValue(node, "Value"));
                    break;

                case AttributeTypes.Money:
                    value = new Money(decimal.Parse(XmlHelper.SelectSingleNodeValue(node, "Value")));
                    break;

                default:
                    value = stringValue;
                    break;
                }
            }
            return(value);
        }
Ejemplo n.º 3
0
        public override object SerializeValue()
        {
            if (_input != null)
            {
                OptionSetValue opt = new OptionSetValue(GetValue());
                opt.Name = jQuery.Select("option:selected", _input).GetText();

                return opt;
            }
            else
                return null;
        }
Ejemplo n.º 4
0
        public static string SerialiseValue(object value, string overrideTypeName)
        {
            string valueXml = "";
            string typeName = overrideTypeName;

            if (typeName == null)
            {
                typeName = value.GetType().Name;
            }

            switch (typeName)
            {
            case "String":
                valueXml += "<b:value i:type=\"" + _addNsPrefix(AttributeTypes.String_) + "\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">";
                valueXml += XmlHelper.Encode((string)value);
                valueXml += "</b:value>";
                break;

            case "Boolean":
            case "bool":
                valueXml += "<b:value i:type=\"" + _addNsPrefix(AttributeTypes.Boolean_) + "\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">";
                valueXml += XmlHelper.Encode(value.ToString());
                valueXml += "</b:value>";
                break;

            case "Date":
                DateTime dateValue  = (DateTime)value;
                string   dateString = null;

                UserSettings settings = OrganizationServiceProxy.UserSettings;
                if (settings != null)
                {
                    DateTime utcDateValue = DateTimeEx.LocalTimeToUTCFromSettings(dateValue, settings);
                    dateString = DateTimeEx.ToXrmString(utcDateValue);
                }
                else
                {
                    dateString = DateTimeEx.ToXrmStringUTC(dateValue);
                }


                valueXml += "<b:value i:type=\"" + _addNsPrefix(AttributeTypes.DateTime_) + "\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">";
                valueXml += XmlHelper.Encode(dateString);
                valueXml += "</b:value>";
                break;

            case "decimal":
                valueXml += "<b:value i:type=\"" + _addNsPrefix(AttributeTypes.Decimal_) + "\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">";
                string decStringValue = null;
                if (value != null)
                {
                    decStringValue = value.ToString();
                }
                valueXml += XmlHelper.Encode(decStringValue);
                valueXml += "</b:value>";
                break;

            case "double":
                valueXml += "<b:value i:type=\"" + _addNsPrefix(AttributeTypes.Double_) + "\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">";
                string doubleStringValue = null;
                if (value != null)
                {
                    doubleStringValue = value.ToString();
                }
                valueXml += XmlHelper.Encode(doubleStringValue);
                valueXml += "</b:value>";
                break;

            case "int":
                valueXml += "<b:value i:type=\"" + _addNsPrefix(AttributeTypes.Int_) + "\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">";
                string intStringValue = null;
                if (value != null)
                {
                    intStringValue = value.ToString();
                }
                valueXml += XmlHelper.Encode(intStringValue);
                valueXml += "</b:value>";
                break;

            case "Guid":
                valueXml += "<b:value i:type=\"" + _addNsPrefix(AttributeTypes.Guid_) + "\" xmlns:c=\"http://schemas.microsoft.com/2003/10/Serialization/\">";
                valueXml += ((Guid)value).Value;
                valueXml += "</b:value>";
                break;

            case AttributeTypes.EntityReference:
                EntityReference entityReferenceValue = (EntityReference)value;

                valueXml += "<b:value i:type=\"" + _addNsPrefix(typeName) + "\">";

                valueXml += "<a:Id>" + entityReferenceValue.Id + "</a:Id><a:LogicalName>" + entityReferenceValue.LogicalName + "</a:LogicalName>";
                valueXml += "</b:value>";
                break;

            case AttributeTypes.OptionSetValue:
                OptionSetValue opt = (OptionSetValue)value;
                if (opt.Value != null)
                {
                    valueXml += "<b:value i:type=\"" + _addNsPrefix(typeName) + "\">";
                    valueXml += "<a:Value>" + opt.Value + "</a:Value>";
                    valueXml += "</b:value>";
                }
                else
                {
                    valueXml += "<b:value i:type=\"" + _addNsPrefix(typeName) + "\" i:nil=\"true\"/>";
                }
                break;

            case AttributeTypes.EntityCollection:
                valueXml += "<b:value i:type=\"" + _addNsPrefix(typeName) + "\">";
                // Serialise each entity in the collection

                // Check the type
                if (value.GetType() != typeof(Array))
                {
                    throw new Exception("An attribute value of type 'EntityCollection' must contain an Array() of Entity instances");
                }
                Array arrayValue = value as Array;

                valueXml += "<a:Entities>";
                for (int i = 0; i < arrayValue.Length; i++)
                {
                    if (arrayValue[i].GetType() != typeof(Entity))
                    {
                        throw new Exception("An attribute value of type 'EntityCollection' must contain an Array() of Entity instances");
                    }

                    valueXml += ((Entity)arrayValue[i]).Serialise(false);
                }
                valueXml += "</a:Entities>";
                valueXml += "</b:value>";
                break;

            case AttributeTypes.Money:
                Money money = (Money)value;
                if (money != null)
                {
                    valueXml += "<b:value i:type=\"" + _addNsPrefix(typeName) + "\">";
                    valueXml += "<a:Value>" + money.Value.ToString() + "</a:Value>";
                    valueXml += "</b:value>";
                }
                else
                {
                    valueXml += "<b:value i:type=\"" + _addNsPrefix(typeName) + "\" i:nil=\"true\"/>";
                }
                break;

            case "EntityFilters":
                int           entityFilterValue  = (int)value;
                List <string> entityFilterValues = new List <string>();
                if ((1 & entityFilterValue) == 1)
                {
                    entityFilterValues.Add("Entity");
                }
                if ((2 & entityFilterValue) == 2)
                {
                    entityFilterValues.Add("Attributes");
                }
                if ((4 & entityFilterValue) == 4)
                {
                    entityFilterValues.Add("Privileges");
                }
                if ((8 & entityFilterValue) == 8)
                {
                    entityFilterValues.Add("Relationships");
                }
                valueXml += "<b:value i:type=\"c:EntityFilters\" xmlns:c=\"http://schemas.microsoft.com/xrm/2011/Metadata\">" + XmlHelper.Encode(entityFilterValues.Join(" ")) + "</b:value>";
                break;

            default:
                valueXml += "<b:value i:nil=\"true\"/>";
                break;
            }
            return(valueXml);
        }
Ejemplo n.º 5
0
 public override void LoadValue(Dictionary<string, object> item)
 {
     OptionSetValue opt = (OptionSetValue)item[_args.Column.Field];
     _defaultValue = opt;
     SetDefaultValue();
 }
        /// <summary>
        /// Gets a <c>Picklist</c> instance who's values are set based on the parameters provided.
        /// </summary>
        /// <param name="entity">The current <c>Entity</c>.</param>
        /// <param name="field">The current <c>DefinitionField</c> for the property being mapped to this <c>Picklist</c>.</param>
        /// <param name="mappedLookupObject">The <c>Dictionary</c> containing the lookup information for the <c>Picklist</c>.</param>
        /// <param name="crm2011Adapter">The <c>CRM2011Adapter</c> to use when calling the CRM web service.</param>
        /// <param name="providedEntityName">The name of the <c>Entity</c> that the current object provider is for.</param>
        /// <returns>A <c>Picklist</c> with it's value property set to the one requested in the <c>Dictionary</c>, if one is found and <c>null</c> otherwise.</returns>
        /// <exception cref="ArgumentException">Thrown if the requested value is not currently in the <c>Picklist</c> within the CRM system.</exception>
        public static OptionSetValue MapPicklist(Entity entity, FieldDefinition field, Dictionary<string, object> mappedLookupObject, DynamicCrmAdapter crm2011Adapter, string providedEntityName)
        {
            if (entity == null || field == null || crm2011Adapter == null)
            {
                throw new AdapterException(string.Format(CultureInfo.CurrentCulture, Resources.ArgumentNullExceptionMessage)) { ExceptionId = AdapterException.SystemExceptionGuid };
            }

            ValidateDictionary(mappedLookupObject);

            if (!mappedLookupObject.Keys.Contains("Value"))
            {
                if (!mappedLookupObject.Keys.Contains("name") || string.IsNullOrEmpty(mappedLookupObject["name"] as string))
                {
                    return null;
                }

                RetrieveAttributeRequest attribReq = new RetrieveAttributeRequest() { EntityLogicalName = entity.LogicalName, LogicalName = field.Name, RetrieveAsIfPublished = true };
                if (IsSpecialAddressPicklist(entity, field))
                {
                    attribReq.EntityLogicalName = providedEntityName;
                    attribReq.LogicalName = string.Format(CultureInfo.CurrentCulture, "address{0}_{1}", ((int?)entity["addressnumber"]).Value.ToString(CultureInfo.CurrentCulture), field.Name);
                }

                // Get the attribute metadata for the state attribute.
                RetrieveAttributeResponse metadataResponse = (RetrieveAttributeResponse)crm2011Adapter.OrganizationService.Execute(attribReq);
                PicklistAttributeMetadata picklistAttrib = (PicklistAttributeMetadata)metadataResponse.AttributeMetadata;

                var picklistValue = from option in picklistAttrib.OptionSet.Options
                                    where option.Label.UserLocalizedLabel.Label.ToUpperInvariant() == mappedLookupObject["name"].ToString().ToUpperInvariant()
                                    select option.Value;

                // ensure that both the returned list and the first item in the returned list are not null or empty.
                if ((picklistValue.Count() > 0) && (picklistValue.First() != null))
                {
                    return new OptionSetValue(picklistValue.First().Value);
                }

                throw new AdapterException(string.Format(CultureInfo.CurrentCulture, Resources.PicklistValueNotFound, mappedLookupObject["name"].ToString(), field.DisplayName, entity.LogicalName)) { ExceptionId = ErrorCodes.PicklistMappingNotFound };
            }

            OptionSetValue mapping = new OptionSetValue();
            SetRelationshipValuesFromDictionary(mappedLookupObject, mapping);
            return mapping;
        }
        /// <summary>
        /// Updates a <c>DynmicEntity</c>'s state and status code property and then calls the service to persist the values
        /// </summary>
        /// <param name="entity">The <c>Entity</c> to set the values on</param>
        /// <param name="state">The state to set</param>
        /// <param name="status">The status to set</param>
        private void ApplyStateAndStatus(Entity entity, OptionSetValue state, OptionSetValue status)
        {
            if (state != null)
            {
                entity["statecode"] = state;
                if (status != null)
                {
                    entity["statuscode"] = status;
                }

                this.SetState(entity);
            }
        }
 /// <summary>
 /// Checks if the state of an entity is already properly set and removes it if it is, otherwise it is set.
 /// </summary>
 /// <param name="dictionary">The <c>Dictionary</c> that contains the state to be set on the entity.</param>
 /// <param name="entity">The CRM <c>Entity</c> to set the state on.</param>
 /// <param name="propertyName">The state code property name.</param>
 /// <param name="adapter">The <see cref="DynamicCrmAdapter"/> to be used for state name to value conversions.</param>
 private static void CheckStateAndStatus(Dictionary<string, object> dictionary, Entity entity, string propertyName, DynamicCrmAdapter adapter)
 {
     int stateToSet = (int)dictionary[propertyName];
     if (!entity.Contains(propertyName) || CRM2011AdapterUtilities.ConvertStateNameToValue(entity[propertyName].ToString(), entity.LogicalName, adapter) != stateToSet)
     {
         entity[propertyName] = new OptionSetValue(stateToSet);
     }
     else
     {
         entity.Attributes.Remove(propertyName);
         if (entity.Contains("statuscode"))
         {
             entity.Attributes.Remove("statuscode");
         }
     }
 }
        /// <summary>
        /// Sets the state code for this instance.
        /// </summary>
        /// <param name="entity">The <c>Entity</c> to set the state code for.</param>
        protected void SetState(Entity entity)
        {
            if (entity != null && entity.Contains("statecode"))
            {
                if (!entity.Contains("statuscode"))
                {
                    entity["statuscode"] = new OptionSetValue(-1);
                }

                OrganizationRequest request = this.GetSetStateRequest(((OptionSetValue)entity["statecode"]).Value, ((OptionSetValue)entity["statuscode"]).Value, entity.Id);
                if (request != null)
                {
                    try
                    {
                        this.CallCrmExecuteWebMethod(request);
                    }
                    catch (AdapterException ae)
                    {
                        if (ae.ExceptionId == ErrorCodes.CrmPlatformException)
                        {
                            ae.ExceptionId = ErrorCodes.StateSettingError;
                        }

                        throw;
                    }
                }
            }
        }