Beispiel #1
0
        /// <summary>
        /// Turns the object into an ObjectInstance
        /// </summary>
        public static ObjectInstance ToObjectInstance(this object o, ScriptEngine engine)
        {
            var result = engine.Object.Construct();

            if (o.GetType() == typeof(ObjectInstance))
            {
                return(o as ObjectInstance); //shouldn't have to... but just in case
            }
            if (o.GetType() == typeof(NameValueCollection) || o.GetType().IsSubclassOf(typeof(NameValueCollection)))
            {
                var nv = (NameValueCollection)o;
                nv.Cast <string>().Select(key => new KeyValuePair <string, object>(key, nv[key])).ToList().ForEach(i => result.SetPropertyValue(i.Key, i.Value, false));
            }
            else
            {
                var props = o.GetType().GetProperties();
                foreach (var item in props)
                {
                    //TODO: Be more smart about the types? (should only be primitives, but could be something else)
                    var value = item.GetValue(o, null);

                    if (value is DateTime)
                    {
                        value = JurassicHelper.ToDateInstance(engine, (DateTime)value);
                    }

                    result.SetPropertyValue(item.Name, value, false);
                }
            }
            return(result);
        }
        public SPFeatureInstance ActivateFeature(object feature, object force)
        {
            var featureId = Guid.Empty;

            if (feature is string)
            {
                featureId = new Guid(feature as string);
            }
            else if (feature is GuidInstance)
            {
                featureId = (feature as GuidInstance).Value;
            }
            else if (feature is SPFeatureInstance)
            {
                featureId = (feature as SPFeatureInstance).Feature.DefinitionId;
            }
            else if (feature is SPFeatureDefinitionInstance)
            {
                featureId = (feature as SPFeatureDefinitionInstance).FeatureDefinition.Id;
            }

            if (featureId == Guid.Empty)
            {
                return(null);
            }

            var forceValue = JurassicHelper.GetTypedArgumentValue(Engine, force, false);

            var activatedFeature = m_site.Features.Add(featureId, forceValue);

            return(new SPFeatureInstance(Engine.Object.InstancePrototype, activatedFeature));
        }
        public ArrayInstance ListEntities(object filterCriteria)
        {
            var criteria = new EntityFilterCriteriaInstance(Engine.Object.InstancePrototype);

            if (filterCriteria is FolderInstance)
            {
                criteria.EntityFilterCriteria.Path = (filterCriteria as FolderInstance).FullPath;
            }
            else if (filterCriteria is string || filterCriteria is StringInstance || filterCriteria is ConcatenatedString)
            {
                criteria.EntityFilterCriteria.Path = filterCriteria.ToString();
            }
            else if (filterCriteria != null && filterCriteria != Null.Value && filterCriteria != Undefined.Value)
            {
                criteria = JurassicHelper.Coerce <EntityFilterCriteriaInstance>(Engine, filterCriteria);
            }

            var result = Engine.Array.Construct();

            foreach (var entity in m_repository.ListEntities(criteria.EntityFilterCriteria))
            {
                ArrayInstance.Push(result, new EntityInstance(Engine, entity));
            }

            return(result);
        }
Beispiel #4
0
        public SortInstance AddSortField(
            [JSDoc("(string) Name of the field to sort by")]
            string fieldName,
            [JSDoc("(bool) (Optional) Indicates whether or not to reverse the sort (false is ascending, true is descending). Default is false.")]
            object reverse,
            [JSDoc("(string) (Optional) Indicates the field type to sort by. Possible values are: string, byte, double, float, int, long, short, string value, doc and score. Default is score.")]
            object fieldType)
        {
            if (fieldName.IsNullOrWhiteSpace())
            {
                throw new JavaScriptException(this.Engine, "Error", "A field name must be specified as the first argument.");
            }

            var reverseValue   = JurassicHelper.GetTypedArgumentValue(this.Engine, reverse, false);
            var fieldTypeValue = JurassicHelper.GetTypedArgumentValue(this.Engine, fieldType, "string");

            SortFieldType fieldTypeEnum;

            if (fieldTypeValue.TryParseEnum(true, out fieldTypeEnum) == false)
            {
                fieldTypeEnum = SortFieldType.String;
            }

            Sort.SortFields.Add(new SortField
            {
                FieldName = fieldName,
                Reverse   = reverseValue,
                Type      = fieldTypeEnum,
            });

            return(this);
        }
        public NumericRangeQueryInstance <float> CreateFloatRangeQuery(string fieldName, object min, object max, bool minInclusive, bool maxInclusive)
        {
            float?floatMin;

            if (min == null || min == Null.Value || min == Undefined.Value)
            {
                floatMin = null;
            }
            else
            {
                floatMin = JurassicHelper.GetTypedArgumentValue(Engine, min, 0);
            }

            float?floatMax;

            if (max == null || max == Null.Value || max == Undefined.Value)
            {
                floatMax = null;
            }
            else
            {
                floatMax = JurassicHelper.GetTypedArgumentValue(Engine, max, 0);
            }

            var query = new FloatNumericRangeQuery
            {
                FieldName    = fieldName,
                Min          = floatMin,
                Max          = floatMax,
                MinInclusive = minInclusive,
                MaxInclusive = maxInclusive
            };

            return(new NumericRangeQueryInstance <float>(Engine.Object.InstancePrototype, query));
        }
Beispiel #6
0
        public int Count(object countParams)
        {
            var parameters = new CountParams(this.Engine.Object.InstancePrototype);

            if (countParams != null && countParams != Null.Value && countParams != Undefined.Value)
            {
                parameters = JurassicHelper.Coerce <CountParams>(this.Engine, countParams);
            }

            if (String.IsNullOrEmpty(parameters.TableName))
            {
                parameters.TableName = GetFullTableName();
            }

            if (String.IsNullOrEmpty(parameters.TableName))
            {
                throw new JavaScriptException(this.Engine, "Error", "A table name must be specified either as a parameter or via the tableName property on the DynamicModel instance.");
            }

            if (String.IsNullOrEmpty(parameters.Where))
            {
                return((int)Scalar(String.Format("SELECT COUNT(*) FROM {0}", parameters.TableName)));
            }

            return((int)Scalar(String.Format("SELECT COUNT(*) FROM {0} WHERE {1}", parameters.TableName, parameters.Where)));
        }
        public object Single(object filterCriteria)
        {
            var criteria = new EntityFilterCriteriaInstance(Engine.Object.InstancePrototype);

            if (filterCriteria is FolderInstance)
            {
                criteria.EntityFilterCriteria.Path = (filterCriteria as FolderInstance).FullPath;
            }
            else if (filterCriteria is string || filterCriteria is StringInstance || filterCriteria is ConcatenatedString)
            {
                criteria.EntityFilterCriteria.Path = filterCriteria.ToString();
            }
            else if (filterCriteria != null && filterCriteria != Null.Value && filterCriteria != Undefined.Value)
            {
                criteria = JurassicHelper.Coerce <EntityFilterCriteriaInstance>(Engine, filterCriteria);
            }

            var result = m_repository.Single(criteria.EntityFilterCriteria);

            if (result == null)
            {
                return(Null.Value);
            }

            return(new EntityInstance(Engine, result));
        }
Beispiel #8
0
        public object Bundle(string bundleDefinitionXml, string fileName, object update, object minify)
        {
            if (String.IsNullOrEmpty(fileName))
            {
                fileName = "bundle.txt";
            }

            var bUpdate = JurassicHelper.GetTypedArgumentValue(Engine, update, true);
            var bMinify = JurassicHelper.GetTypedArgumentValue(Engine, minify, false);

            var doc = new XmlDocument();

            doc.LoadXml(bundleDefinitionXml);
            var bundleText = GenerateBundleFromBundleDefinition(fileName, doc, bUpdate, bMinify);

            var bytes = new Base64EncodedByteArrayInstance(Engine.Object.InstancePrototype, Encoding.UTF8.GetBytes(bundleText))
            {
                FileName = fileName,
                MimeType = StringHelper.GetMimeTypeFromFileName(fileName),
            };

            var result = Engine.Object.Construct();

            result.SetPropertyValue("lastModified", JurassicHelper.ToDateInstance(Engine, FileModifiedDates.Values.Max(v => v.Item1)), false);
            result.SetPropertyValue("data", bytes, false);
            return(result);
        }
        public void LoadFromJson(object array, object hasHeader)
        {
            if (array == null || array == Null.Value || array == Undefined.Value || (array is ArrayInstance) == false ||
                (array as ArrayInstance).Length == 0)
            {
                return;
            }

            var jsonArray = array as ArrayInstance;

            var           bHasHeader = JurassicHelper.GetTypedArgumentValue(this.Engine, hasHeader, true);
            List <string> header     = null;

            //If we have a header, populate the first row with header info.
            var currentRow = 1;

            if (bHasHeader)
            {
                var firstRecord = jsonArray[0] as ObjectInstance;
                if (firstRecord == null)
                {
                    return;
                }

                header = firstRecord.Properties
                         .Select(property => property.Name)
                         .ToList();

                for (int i = 1; i < header.Count + 1; i++)
                {
                    m_excelWorksheet.Cells[currentRow, i].Value = header[i - 1];
                }
                currentRow++;
            }

            foreach (var value in jsonArray.ElementValues.OfType <ObjectInstance>())
            {
                if (header == null)
                {
                    var properties = value.Properties.ToList();
                    for (var c = 1; c < properties.Count + 1; c++)
                    {
                        var propertyValue = properties[c - 1];
                        SetValue(currentRow, c, propertyValue.Value);
                    }
                }
                else
                {
                    for (var c = 1; c < header.Count + 1; c++)
                    {
                        var key           = header[c - 1];
                        var propertyValue = value[key];
                        SetValue(currentRow, c, propertyValue);
                    }
                }

                currentRow++;
            }
        }
Beispiel #10
0
 public DocumentStoreInstance Construct(object creationInfo)
 {
     if (creationInfo != null && creationInfo != Null.Value && creationInfo != Undefined.Value &&
         creationInfo is ObjectInstance)
     {
         var result = JurassicHelper.Coerce <DocumentStoreInstance>(this.Engine, creationInfo);
         return(result);
     }
     return(new DocumentStoreInstance(this.InstancePrototype));
 }
        public static double Utc(ScriptEngine engine, int year, int month, [DefaultParameterValue(1)] object dayArg, [DefaultParameterValue(0)] object hourArg,
                                 [DefaultParameterValue(0)] object minuteArg, [DefaultParameterValue(0)] object secondArg, [DefaultParameterValue(0)] object millisecondArg)
        {
            var day         = JurassicHelper.GetTypedArgumentValue(engine, dayArg, 1);
            var hour        = JurassicHelper.GetTypedArgumentValue(engine, hourArg, 0);
            var minute      = JurassicHelper.GetTypedArgumentValue(engine, minuteArg, 0);
            var second      = JurassicHelper.GetTypedArgumentValue(engine, secondArg, 0);
            var millisecond = JurassicHelper.GetTypedArgumentValue(engine, millisecondArg, 0);

            return(DateInstance.Utc(engine, year, month, day, hour, minute, second, millisecond));
        }
Beispiel #12
0
            public override object CallLateBound(object thisObject, params object[] argumentValues)
            {
                var contentObject = argumentValues.ElementAtOrDefault(0);

                if (contentObject == Undefined.Value ||
                    contentObject == Null.Value || contentObject == null)
                {
                    return(thisObject);
                }

                var mergeSettings             = argumentValues.ElementAtOrDefault(1);
                JsonMergeSettingsInstance jms = null;

                if (mergeSettings != Undefined.Value && mergeSettings != Null.Value && mergeSettings != null)
                {
                    if (mergeSettings is JsonMergeSettingsInstance)
                    {
                        jms = (mergeSettings as JsonMergeSettingsInstance);
                    }
                    else
                    {
                        jms = JurassicHelper.Coerce <JsonMergeSettingsInstance>(this.Engine, mergeSettings);
                    }
                }

                var s1 = JSONObject.Stringify(this.Engine, thisObject, null, null);
                var s2 = JSONObject.Stringify(this.Engine, contentObject, null, null);

                if (TypeUtilities.IsObject(thisObject) == false && TypeUtilities.IsArray(thisObject) == false)
                {
                    throw new JavaScriptException(this.Engine, "Error", "This object must either be an object or an array.");
                }

                if (TypeUtilities.IsObject(contentObject) == false && TypeUtilities.IsArray(contentObject) == false)
                {
                    throw new JavaScriptException(this.Engine, "Error", "Content object must either be an object or an array.");
                }

                var o1 = (JContainer)JToken.Parse(s1);
                var o2 = (JContainer)JToken.Parse(s2);

                if (jms != null)
                {
                    o1.Merge(o2, jms.JsonMergeSettings);
                }
                else
                {
                    o1.Merge(o2);
                }

                var result = JSONObject.Parse(this.Engine, o1.ToString(), null);

                return(result);
            }
        public DateInstance GetServerNow(SPWebInstance web)
        {
            if (web == null)
            {
                throw new JavaScriptException(this.Engine, "Error", "A web must be specified as the first parameter.");
            }

            var result = SPUtility.GetServerNow(web.Web);

            return(JurassicHelper.ToDateInstance(this.Engine, result));
        }
Beispiel #14
0
        public ObjectInstance Paged(object pagedParams)
        {
            PagedParams parameters = new PagedParams(this.Engine.Object.InstancePrototype);

            if (pagedParams != null && pagedParams != Undefined.Value && pagedParams != Null.Value)
            {
                parameters = JurassicHelper.Coerce <PagedParams>(this.Engine, pagedParams);
            }

            return(BuildPagedResult(parameters));
        }
Beispiel #15
0
        public static ObjectInstance RecordToObjectInstance(this IDataReader rdr, ScriptEngine engine)
        {
            ObjectInstance e = engine.Object.Construct();

            for (int i = 0; i < rdr.FieldCount; i++)
            {
                object propertyValue;
                var    value = rdr[i];

                if (DBNull.Value.Equals(value))
                {
                    propertyValue = Null.Value;
                }
                else if (value is DateTime)
                {
                    propertyValue = JurassicHelper.ToDateInstance(engine, (DateTime)value);
                }
                else if (value is Byte)
                {
                    propertyValue = Convert.ToInt32((Byte)value);
                }
                else if (value is Int16)
                {
                    propertyValue = Convert.ToInt32((Int16)value);
                }
                else if (value is Int64)
                {
                    propertyValue = Convert.ToDouble((Int64)value);
                }
                else if (value is decimal)
                {
                    propertyValue = Convert.ToDouble((decimal)value);
                }
                else if (value is Guid)
                {
                    propertyValue = ((Guid)value).ToString();
                }
                else if (value is Byte[])
                {
                    propertyValue = new Base64EncodedByteArrayInstance(engine.Object.InstancePrototype, (Byte[])value);
                }
                else if (value.GetType().FullName == "Microsoft.SqlServer.Types.SqlHierarchyId")
                {
                    propertyValue = value.ToString();
                }
                else
                {
                    propertyValue = value;
                }

                e.SetPropertyValue(rdr.GetName(i), propertyValue, false);
            }
            return(e);
        }
Beispiel #16
0
        public int Delete(object deleteParams)
        {
            if (deleteParams == null || deleteParams == Null.Value || deleteParams == Undefined.Value)
            {
                throw new JavaScriptException(this.Engine, "Error", "Must specify an object with where or key");
            }

            var parameters = JurassicHelper.Coerce <DeleteParams>(this.Engine, deleteParams);

            int result = Execute(CreateDeleteCommand(parameters));

            return(result);
        }
Beispiel #17
0
        public ArrayInstance All(object allParams)
        {
            var parameters = new AllParams(this.Engine.Object.InstancePrototype);

            if (allParams != null && allParams != Undefined.Value && allParams != Null.Value)
            {
                parameters = JurassicHelper.Coerce <AllParams>(this.Engine, allParams);
            }

            string sql = BuildSelect(parameters.Where, parameters.OrderBy, parameters.Limit);

            return(Query(string.Format(sql, parameters.Columns, GetFullTableName()), parameters.Args));
        }
        public void Compile(string pattern, [DefaultParameterValue(null)] object flagsArg)
        {
            var flags = JurassicHelper.GetTypedArgumentValue <string>(this.Engine, flagsArg, null);

            this.m_value = new Regex(pattern, ParseFlags(flags) | RegexOptions.Compiled);

            // Update the javascript properties.
            this.FastSetProperty("source", pattern, PropertyAttributes.Sealed, false);
            this.FastSetProperty("global", this.Global, PropertyAttributes.Sealed, false);
            this.FastSetProperty("multiline", this.Multiline, PropertyAttributes.Sealed, false);
            this.FastSetProperty("ignoreCase", this.IgnoreCase, PropertyAttributes.Sealed, false);
            this.LastIndex = 0;
        }
Beispiel #19
0
        public string ToStringJS([DefaultParameterValue(10)] object radixArg)
        {
            var radix = JurassicHelper.GetTypedArgumentValue(this.Engine, radixArg, 10);

            // Check the parameter is in range.
            if (radix < 2 || radix > 36)
            {
                throw new JavaScriptException(this.Engine, "RangeError", "The radix must be between 2 and 36, inclusive.");
            }

            // NumberFormatter does the hard work.
            return(NumberFormatter.ToString(this.m_value, radix, NumberFormatter.Style.Regular, 0));
        }
Beispiel #20
0
        public string ToFixed([DefaultParameterValue(0)] object fractionDigitsArg)
        {
            var fractionDigits = JurassicHelper.GetTypedArgumentValue(this.Engine, fractionDigitsArg, 0);

            // Check the parameter is within range.
            if (fractionDigits < 0 || fractionDigits > 20)
            {
                throw new JavaScriptException(this.Engine, "RangeError", "toFixed() argument must be between 0 and 20.");
            }

            // NumberFormatter does the hard work.
            return(NumberFormatter.ToString(this.m_value, 10, NumberFormatter.Style.Fixed, fractionDigits));
        }
Beispiel #21
0
        public void Time([DefaultParameterValue("")] object nameArg)
        {
            var name = JurassicHelper.GetTypedArgumentValue(this.Engine, nameArg, "") ?? string.Empty;

            if (this.m_timers == null)
            {
                this.m_timers = new Dictionary <string, Stopwatch>();
            }
            if (this.m_timers.ContainsKey(name))
            {
                return;
            }
            this.m_timers.Add(name, Stopwatch.StartNew());
        }
        public TermsFilterInstance CreateTermsFilter(object fieldName, object text)
        {
            var fieldNameValue = JurassicHelper.GetTypedArgumentValue(Engine, fieldName, String.Empty);
            var textValue      = JurassicHelper.GetTypedArgumentValue(Engine, text, String.Empty);

            var termsFilter = new TermsFilter();

            if (fieldNameValue.IsNullOrWhiteSpace() == false && textValue.IsNullOrWhiteSpace() == false)
            {
                termsFilter.Terms.Add(new Term {
                    FieldName = fieldNameValue, Value = textValue
                });
            }

            return(new TermsFilterInstance(Engine.Object.InstancePrototype, termsFilter));
        }
        public object GetValue(int row, int column)
        {
            var value = m_excelWorksheet.GetValue(row, column);

            if (value is int || value is string || value is double || value is bool)
            {
                return(value);
            }

            if (value is DateTime)
            {
                return(JurassicHelper.ToDateInstance(this.Engine, (DateTime)value));
            }

            return(m_excelWorksheet.GetValue <string>(row, column));
        }
Beispiel #24
0
        public static double ParseInt(ScriptEngine engine, string input, [DefaultParameterValue(0.0)] object radixArg)
        {
            var radix = JurassicHelper.GetTypedArgumentValue(engine, radixArg, 0.0);

            // Check for a valid radix.
            // Note: this is the only function that uses TypeConverter.ToInt32() for parameter
            // conversion (as opposed to the normal method which is TypeConverter.ToInteger() so
            // the radix parameter must be converted to an integer in code.
            int radix2 = TypeConverter.ToInt32(radix);

            if (radix2 < 0 || radix2 == 1 || radix2 > 36)
            {
                return(double.NaN);
            }

            return(NumberParser.ParseInt(input, radix2, engine.CompatibilityMode == CompatibilityMode.ECMAScript3));
        }
Beispiel #25
0
        public void TimeEnd([DefaultParameterValue("")] object nameArg)
        {
            var name = JurassicHelper.GetTypedArgumentValue(this.Engine, nameArg, "") ?? string.Empty;

            if (this.m_timers == null || this.m_timers.ContainsKey(name) == false)
            {
                return;
            }
            var stopwatch = this.m_timers[name];

            Log(FirebugConsoleMessageStyle.Regular,
                string.IsNullOrEmpty(name)
            ? string.Format("{0}ms", stopwatch.ElapsedMilliseconds)
            : string.Format("{0}: {1}ms", name, stopwatch.ElapsedMilliseconds));

            this.m_timers.Remove(name);
        }
        public static ObjectInstance Create(ScriptEngine engine, object prototype, [DefaultParameterValue(null)] object propertiesArg)
        {
            var properties = JurassicHelper.GetTypedArgumentValue <ObjectInstance>(engine, propertiesArg, null);

            if ((prototype is ObjectInstance) == false && prototype != Null.Value)
            {
                throw new JavaScriptException(engine, "TypeError", "object prototype must be an object or null");
            }
            ObjectInstance result = prototype == Null.Value
                                ? ObjectInstance.CreateRootObject(engine)
                                : ObjectInstance.CreateRawObject((ObjectInstance)prototype);

            if (properties != null)
            {
                DefineProperties(result, properties);
            }
            return(result);
        }
Beispiel #27
0
        protected override ObjectSettings Unwrap(ObjectInstance objectSettings)
        {
            if (objectSettings == null)
            {
                return(null);
            }

            var os = objectSettings as ObjectSettingsInstance;

            if (os != null)
            {
                return(os.ObjectSettings);
            }

            var os2 = JurassicHelper.Coerce <ObjectSettingsInstance>(Engine, objectSettings);

            return(os2.ObjectSettings);
        }
Beispiel #28
0
        public static ArrayInstance Split(ScriptEngine engine, string thisObject, object separator, [DefaultParameterValue(4294967295.0)] object limitArg)
        {
            var limit = JurassicHelper.GetTypedArgumentValue(engine, limitArg, 4294967295.0);

            // Limit defaults to unlimited.  Note the ToUint32() conversion.
            uint limit2 = uint.MaxValue;

            if (TypeUtilities.IsUndefined(limit) == false)
            {
                limit2 = TypeConverter.ToUint32(limit);
            }

            // Call separate methods, depending on whether the separator is a regular expression.
            if (separator is RegExpInstance)
            {
                return(Split(thisObject, (RegExpInstance)separator, limit2));
            }
            return(Split(engine, thisObject, TypeConverter.ToString(separator), limit2));
        }
Beispiel #29
0
        protected override IBaristaCookie Unwrap(ObjectInstance cookie)
        {
            if (cookie == null)
            {
                return(null);
            }

            //If c is cookie, that's good for me.
            var c = cookie as BaristaCookieInstance;

            if (c != null)
            {
                return(c.BaristaCookie);
            }

            var os2 = JurassicHelper.Coerce <BaristaCookieInstance>(Engine, cookie);

            return(os2.BaristaCookie);
        }
Beispiel #30
0
        public string PutIndex(object name, object indexDefinition, object overwrite)
        {
            if (name == null || name == Undefined.Value || name == Null.Value)
            {
                throw new JavaScriptException(this.Engine, "Error", "The first argument must contain the index name.");
            }

            if (indexDefinition == null || indexDefinition == Undefined.Value || indexDefinition == Null.Value)
            {
                throw new JavaScriptException(this.Engine, "Error", "The second argument must contain the index definition.");
            }

            var strName = TypeConverter.ToString(name);

            RavenDB.Abstractions.Indexing.IndexDefinition objIndexDefinition;

            if (indexDefinition is IndexDefinitionInstance)
            {
                objIndexDefinition = (indexDefinition as IndexDefinitionInstance).IndexDefinition;
            }
            else if (indexDefinition is ObjectInstance)
            {
                objIndexDefinition = JurassicHelper.Coerce <IndexDefinitionInstance>(this.Engine, indexDefinition).IndexDefinition;
            }
            else
            {
                throw new JavaScriptException(this.Engine, "Error", "The second argument must contain either an instance of IndexDefinition or a object that can be converted");
            }

            string result;

            if (overwrite != null && overwrite != Null.Value && overwrite != Undefined.Value)
            {
                result = m_databaseCommands.PutIndex(strName, objIndexDefinition, TypeConverter.ToBoolean(overwrite));
            }
            else
            {
                result = m_databaseCommands.PutIndex(strName, objIndexDefinition);
            }

            return(result);
        }