Stringify() private method

private Stringify ( int depth, StringBuilder builder, bool pretty = false ) : void
depth int
builder StringBuilder
pretty bool
return void
Esempio n. 1
0
            public override object CallLateBound(object thisObject, params object[] argumentValues)
            {
                var arg = argumentValues.ElementAtOrDefault(0);

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

                var reviver  = argumentValues.ElementAtOrDefault(1);
                var settings = argumentValues.ElementAtOrDefault(2);

                var jsonSerializerSettings = new JsonSerializerSettings();

                if (settings != null)
                {
                    var settingsJson = JSONObject.Stringify(this.Engine, settings, null, null);
                    JsonConvert.PopulateObject(settingsJson, jsonSerializerSettings);
                }

                var value = TypeConverter.ToString(arg);


                var obj    = JsonConvert.DeserializeObject(value, jsonSerializerSettings);
                var value2 = JsonConvert.SerializeObject(obj, Formatting.None, jsonSerializerSettings);

                return(JSONObject.Parse(this.Engine, value2, reviver));
            }
Esempio n. 2
0
        /// <summary>
        /// Given two json strings perform a diff on the objects and return the result as a formatted json string.
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <param name="settings"></param>
        /// <returns></returns>
        public static string Diff(string a, string b, JsonSerializerSettings settings)
        {
            if (a.ToLowerInvariant() == "null" && b.ToLowerInvariant() == "null")
            {
                return("null");
            }
            if (a.ToLowerInvariant() == "null")
            {
                return(b);
            }
            if (b.ToLowerInvariant() == "null")
            {
                return(a);
            }

            var engine = JsonHelper.Engine;

            engine.Execute("var a = " + a + ";");
            engine.Execute("var b = " + b + ";");
            var result       = engine.Evaluate("jsonDataHandler.diff(a, b);");
            var stringResult = JSONObject.Stringify(engine, result, null, null);

            object parsedJson = JsonConvert.DeserializeObject(stringResult);

            return(JsonConvert.SerializeObject(parsedJson, Formatting.Indented, settings));
        }
Esempio n. 3
0
            public override object CallLateBound(object thisObject, params object[] argumentValues)
            {
                var schema = argumentValues.ElementAtOrDefault(0);

                if (schema == Undefined.Value ||
                    schema == Null.Value || schema == null)
                {
                    return(true);
                }

                JsonSchema jsSchema;

                if (schema is JsonSchemaInstance)
                {
                    jsSchema = (schema as JsonSchemaInstance).JsonSchema;
                }
                else
                {
                    jsSchema = JsonSchema.Parse(JSONObject.Stringify(this.Engine, schema, null, null));
                }

                var s1 = JSONObject.Stringify(this.Engine, thisObject, null, null);
                var o1 = JToken.Parse(s1);

                return(o1.IsValid(jsSchema));
            }
Esempio n. 4
0
        /// <summary>
        /// Processes worker process requests.
        /// </summary>
        /// <param name="request"> The request to process. </param>
        public WorkerProcessResponse ProcessRequest(WorkerProcessRequest request)
        {
            var engine = new ScriptEngine();

            var response = new WorkerProcessResponse();

            try
            {
                // Execute the provided script.
                object result = engine.Evaluate(request.Script);
                response.JsonResult = JSONObject.Stringify(engine, result);
                if (request.VariablesToReturn != null)
                {
                    response.Variables = new Dictionary <string, string>();
                    foreach (var variableName in request.VariablesToReturn)
                    {
                        response.Variables[variableName] = engine.GetGlobalValue <string>(variableName);
                    }
                }
            }
            catch (Exception e)
            {
                // There was an error.
                response.ErrorType    = e.GetType().Name;
                response.ErrorMessage = e.Message;
            }

            return(response);
        }
        public void SetPropertyKeyValue(string key, object value)
        {
            if (value == null || value == Undefined.Value || value == Null.Value)
            {
                throw new ArgumentNullException("value");
            }

            string stringValue;

            if (value is ObjectInstance)
            {
                stringValue = JSONObject.Stringify(Engine, value, null, null);
            }
            else
            {
                stringValue = value.ToString();
            }

            if (m_iisWebServiceApplication.Properties.ContainsKey(key))
            {
                m_iisWebServiceApplication.Properties[key] = stringValue;
            }
            else
            {
                m_iisWebServiceApplication.Properties.Add(key, stringValue);
            }

            m_iisWebServiceApplication.Update();
        }
Esempio n. 6
0
            public override object CallLateBound(object thisObject, params object[] argumentValues)
            {
                var path = argumentValues.ElementAtOrDefault(0);

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

                var sPath = TypeConverter.ToString(path);

                var s1 = JSONObject.Stringify(this.Engine, thisObject, null, null);
                var o1 = JToken.Parse(s1);

                var tokens = o1.SelectTokens(sPath, false);
                var result = this.Engine.Array.Construct();

                foreach (var token in tokens)
                {
                    ArrayInstance.Push(result, JSONObject.Parse(this.Engine, token.ToString(), null));
                }

                return(result);
            }
Esempio n. 7
0
        public PutResultInstance Put(object key, object eTag, object document, object metadata)
        {
            if (key == null || key == Undefined.Value || key == Null.Value)
            {
                throw new JavaScriptException(this.Engine, "Error", "The first argument must contain a key.");
            }

            if (document == null || document == Undefined.Value || document == Null.Value)
            {
                throw new JavaScriptException(this.Engine, "Error", "The third argument must contain a document.");
            }

            var strKey   = TypeConverter.ToString(key);
            var guidETag = GetETagValue(eTag);

            var roDocument = RavenDB.Json.Linq.RavenJObject.Parse(JSONObject.Stringify(this.Engine, document, null, null));

            RavenDB.Json.Linq.RavenJObject roMetadata = null;
            if (metadata != null && metadata != Null.Value && metadata != Undefined.Value)
            {
                roMetadata = RavenDB.Json.Linq.RavenJObject.Parse(JSONObject.Stringify(this.Engine, metadata, null, null));
            }

            var result = m_databaseCommands.Put(strKey, guidETag, roDocument, roMetadata);

            return(new PutResultInstance(this.Engine.Object.InstancePrototype, result));
        }
Esempio n. 8
0
        public void SendPacket(object a)
        {
            if (++script.Counters["json"] > 100)
            {
                throw new JavaScriptException(Engine.Error.Construct("Send packet limit reached"), 0, null);
            }

            string tmp = string.Empty;

            if (a is ObjectInstance)
            {
                tmp = JSONObject.Stringify(Engine, a);
            }

            else if (a is string || a is ConcatenatedString)
            {
                tmp = a.ToString();
            }

            if (!string.IsNullOrEmpty(tmp))
            {
                Match match = Regex.Match(tmp, "(['\"]*)id\\1:\\s*(['\"]*)(\\d+)\\2", RegexOptions.Singleline | RegexOptions.IgnoreCase);
                if (match.Success)
                {
                    if (byte.TryParse(match.Groups[3].Value, out byte id))
                    {
                        IPacket p = Room.Formatter.Unformat(id, tmp);
                        if (p != null)
                        {
                            Client.SendPacket(p);
                        }
                    }
                }
            }
        }
Esempio n. 9
0
        public static string GetJsonValueForKey(string html, string key)
        {
            string value = string.Empty;

            try
            {
                // Getting json string from variable
                HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                doc.LoadHtml(html);
                var script = doc.DocumentNode.Descendants()
                             .Where(n => n.Name == "script")
                             .First().InnerText;

                // Return the data of spect and stringify it into a proper JSON object
                var engine = new Jurassic.ScriptEngine();
                var result = engine.Evaluate("(function() { " + script + " return gm_init_vars; })()");
                var json   = JSONObject.Stringify(engine, result);

                // Json parsing
                value = GetJsonObjectValue(json, key);
            }
            catch (Exception ex)
            {
                ex.ToString();
                throw;
            }

            return(value);
        }
Esempio n. 10
0
        /// <summary>
        /// Helper method that supports duck typing of Jurassic Object Instances with their .Net counterparts.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="engine"></param>
        /// <param name="instance"></param>
        /// <returns></returns>
        public static T Coerce <T>(ScriptEngine engine, object instance)
            where T : ObjectInstance
        {
            if (instance == null || instance == Null.Value || instance == Undefined.Value)
            {
                return(null);
            }

            if (instance is T)
            {
                return(instance as T);
            }

            var objectInstance   = instance as ObjectInstance;
            var serializedObject = objectInstance != null
                                     ? JSONObject.Stringify(engine, objectInstance, null, null)
                                     : JsonConvert.SerializeObject(instance);

            var type = typeof(T);

            //If the target type contains a constructor that accepts an ObjectInstance as the parameter, create a new instance of the target type and
            //supply the instance prototype. Otherwise, create an instance using the default constructor.
            var objectInstanceConstructor = type.GetConstructor(new[] { typeof(ObjectInstance) });

            if (objectInstanceConstructor != null)
            {
                var result = (T)Activator.CreateInstance(typeof(T), engine.Object.InstancePrototype);
                JsonConvert.PopulateObject(serializedObject, result, new JsonSerializerSettings
                {
                    Converters = { new ObjectInstanceConverter(engine) }
                });

                return(result);
            }

            var objectInstanceConstructor2 = type.GetConstructor(new[] { typeof(ScriptEngine) });

            if (objectInstanceConstructor2 != null)
            {
                var result = (T)Activator.CreateInstance(typeof(T), engine);
                JsonConvert.PopulateObject(serializedObject, result, new JsonSerializerSettings
                {
                    Converters = { new ObjectInstanceConverter(engine) }
                });

                return(result);
            }

            var finalResult = (T)Activator.CreateInstance(typeof(T));

            JsonConvert.PopulateObject(serializedObject, finalResult, new JsonSerializerSettings
            {
                Converters = { new ObjectInstanceConverter(engine) }
            });

            return(finalResult);
        }
Esempio n. 11
0
        public string ToJson(Topic t)
        {
            IToJson tj;

            if ((tj = t.value as IToJson) != null)
            {
                return(tj.ToJson());
            }
            return(JSONObject.Stringify(Engine, t.value));
        }
Esempio n. 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 void SetValue(int row, int column, object value)
 {
     if (TypeUtilities.IsPrimitive(value))
     {
         m_excelWorksheet.SetValue(row, column, value);
     }
     else
     {
         var strValue = JSONObject.Stringify(this.Engine, value, null, null);
         m_excelWorksheet.SetValue(row, column, strValue);
     }
 }
 public void SetValue(object value)
 {
     if (TypeUtilities.IsPrimitive(value))
     {
         m_excelRange.Value = value;
     }
     else
     {
         var strValue = JSONObject.Stringify(this.Engine, value, null, null);
         m_excelRange.Value = strValue;
     }
 }
        public object UpdateEntity(object entityId, object eTag, object data)
        {
            if (entityId == Null.Value || entityId == Undefined.Value || entityId == null)
            {
                throw new JavaScriptException(Engine, "Error", "Entity Id must be specified.");
            }

            var id = ConvertFromJsObjectToGuid(entityId);

            string stringData;
            var    stringETag = "";

            if (eTag != Null.Value && eTag != Undefined.Value)
            {
                stringETag = eTag.ToString();
            }

            if (data == Null.Value || data == Undefined.Value || data == null)
            {
                if (entityId is EntityInstance)
                {
                    var entityArg = entityId as EntityInstance;
                    m_repository.UpdateEntity(entityArg.Entity.Id, entityArg.Entity.Title, entityArg.Entity.Description, entityArg.Entity.Namespace);

                    stringData = (entityId as EntityInstance).Entity.Data;
                }
                else
                {
                    throw new InvalidOperationException(
                              "A data parameter must be specified if the first parameter is not an instance of an Entity object.");
                }
            }
            else if (data is ObjectInstance)
            {
                // ReSharper disable RedundantArgumentDefaultValue
                stringData = JSONObject.Stringify(Engine, data, null, null);
            }
            // ReSharper restore RedundantArgumentDefaultValue
            else
            {
                stringData = data.ToString();
            }

            var result = m_repository.UpdateEntityData(id, stringETag, stringData);

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

            return(new EntityInstance(Engine, result));
        }
        public JsonSchemaInstance Parse(object schema)
        {
            if (schema == null || schema == Undefined.Value || schema == Null.Value)
            {
                throw new JavaScriptException(this.Engine, "Error", "Schema must be specified as the first object.");
            }

            var schemaString = TypeUtilities.IsString(schema)
                ? TypeConverter.ToString(schema)
                : JSONObject.Stringify(this.Engine, schema, null, null);

            return(new JsonSchemaInstance(this.Engine, JsonSchema.Parse(schemaString)));
        }
        public EntityPartInstance CreateEntityPart(object entityId, object partName, object category, object data)
        {
            if (entityId == null || entityId == Null.Value || entityId == Undefined.Value)
            {
                throw new JavaScriptException(Engine, "Error", "An entity id or an entity must be defined as the first parameter.");
            }

            if (partName == null || partName == Null.Value || partName == Undefined.Value)
            {
                throw new JavaScriptException(Engine, "Error", "The name of the desired entity part must be defined as the second parameter.");
            }

            var stringCategory = "";
            var stringData     = "";

            string stringPartName = partName.ToString();

            if (String.IsNullOrEmpty(stringPartName))
            {
                throw new JavaScriptException(Engine, "Error", "When creating an entity part, a part name must be specified.");
            }

            if (category != Null.Value && category != Undefined.Value || category != null)
            {
                stringCategory = category.ToString();
            }

            if (data is ObjectInstance)
            {
                // ReSharper disable RedundantArgumentDefaultValue
                stringData = JSONObject.Stringify(Engine, data, null, null);
            }
            // ReSharper restore RedundantArgumentDefaultValue
            else if (data != null)
            {
                stringData = data.ToString();
            }

            var id = ConvertFromJsObjectToGuid(entityId);

            try
            {
                var result = m_repository.CreateEntityPart(id, stringPartName, stringCategory, stringData);
                return(new EntityPartInstance(Engine, result));
            }
            catch (EntityPartExistsException)
            {
                throw new JavaScriptException(Engine, "Error", "An entity part with the specified name already exists.");
            }
        }
Esempio n. 18
0
        /// <summary>
        /// Given two json strings, merge a with b and return the result as a formatted json string.
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <param name="settings"></param>
        /// <returns></returns>
        public static string Merge(string a, string b, JsonSerializerSettings settings)
        {
            var engine = JsonHelper.Engine;

            engine.Execute("var a = " + a + ";");
            engine.Execute("var b = " + b + ";");
            engine.Execute("jsonDataHandler.merge(a, b);");
            var result       = engine.Evaluate("a;");
            var stringResult = JSONObject.Stringify(engine, result, null, null);

            var parsedJson = JsonConvert.DeserializeObject(stringResult);

            return(JsonConvert.SerializeObject(parsedJson, Formatting.Indented, settings));
        }
Esempio n. 19
0
        public IHttpActionResult QueryByLink(string link)
        {
            ApiResponse res = new ApiResponse();

            try
            {
                ServicePointManager.Expect100Continue = true;
                ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls12;
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(link);
                req.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36";
                req.Host      = "www.hepsiburada.com";
                req.Referer   = "www.hepsiburada.com";
                var response       = req.GetResponse();
                var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(responseString);
                var nodes = doc.DocumentNode.Descendants();

                List <Product> list          = new List <Product>();
                var            scripts       = nodes.Where(x => x.Name == "script").ToList();
                var            script        = scripts.Where(x => x.InnerHtml.Contains("viewModelName")).FirstOrDefault();
                ScriptEngine   eng           = new ScriptEngine();
                var            scriptContent = script.InnerHtml;

                var result = eng.Evaluate("(function(){ " + scriptContent + "; return productModel; })()");
                var json   = JSONObject.Stringify(eng, result);

                dynamic productObj = JsonConvert.DeserializeObject(json);
                var     listings   = productObj.product.listings;
                foreach (var item in listings)
                {
                    Product p = new Product();
                    p.SellerName = item.merchantName;
                    p.Price      = item.priceText;
                    list.Add(p);
                }

                res.Data        = list;
                res.Status      = true;
                res.Description = "Success";
                return(Json(res));
            }
            catch (Exception ex)
            {
                res.Status      = false;
                res.Description = "Hata Mesajı : " + ex.Message;
                return(Json(res));
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Given two objects, perform a diff on the objects and return the result as a new object that contains the differences.
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <param name="settings"></param>
        /// <returns></returns>
        public static T Diff <T>(T a, T b, JsonSerializerSettings settings)
        {
            var jsonA = JsonConvert.SerializeObject(a, Formatting.None, settings);
            var jsonB = JsonConvert.SerializeObject(b, settings);

            var engine = JsonHelper.Engine;

            engine.Execute("var a = " + jsonA + ";");
            engine.Execute("var b = " + jsonB + ";");
            var result       = engine.Evaluate("jsonDataHandler.diff(a, b);");
            var stringResult = JSONObject.Stringify(engine, result, null, null);

            return(JsonConvert.DeserializeObject <T>(stringResult, settings));
        }
Esempio n. 21
0
        public void SendPacket(object a, object b)
        {
            if (++script.Counters["json"] > 100)
                throw new JavaScriptException(Engine.Error.Construct("Send packet limit reached"), 0, null);

            if (b is Undefined) {
                string tmp = a is ObjectInstance ? JSONObject.Stringify(Engine, a) : a.ToString();
                Match match = Regex.Match(tmp, "(['\"]*)id\\1:\\s*(['\"]*)(\\d+)\\2", RegexOptions.Singleline | RegexOptions.IgnoreCase);
                if (match.Success) {
                    if (byte.TryParse(match.Groups[3].Value, out byte id)) {
                        IPacket p = Formatter.Unformat(id, tmp);
                        if (p != null) server.SendPacket(p);
                        return;
                    }
                }
            }
            else {
                string tmp = b is ObjectInstance ? JSONObject.Stringify(Engine, b) : b.ToString();
                Match match = Regex.Match(tmp, "(['\"]*)id\\1:\\s*(['\"]*)(\\d+)\\2", RegexOptions.Singleline | RegexOptions.IgnoreCase);
                if (match.Success) {
                    if (a is User user) {
                        if (byte.TryParse(match.Groups[3].Value, out byte id)) {
                            IPacket p = Formatter.Unformat(id, tmp);
                            if (p != null) server.SendPacket(user.Client, p);
                            return;
                        }
                    }
                    else if (a is FunctionInstance predicate) {
                        if (byte.TryParse(match.Groups[3].Value, out byte id)) {
                            IPacket p = Formatter.Unformat(id, tmp);
                            if (p != null) {
                                for (int i = 0; i < this.script.Room.Users.Items.Count; i++) {
                                    user = (User)this.script.Room.Users.Items[i];
                                    try {
                                        object ret = predicate.Call(this, user);
                                        if (TypeConverter.ConvertTo<bool>(Engine, ret))
                                            server.SendPacket(user.Client, p);
                                    }
                                    catch (JavaScriptException jex) {
                                        JurassicPlugin.Self.OnError(jex);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
 public void SetValueAtAddress(string address, object value)
 {
     if (TypeUtilities.IsPrimitive(value))
     {
         m_excelWorksheet.SetValue(address, value);
     }
     else if (value is DateInstance)
     {
         m_excelWorksheet.SetValue(address, DateTime.Parse((value as DateInstance).ToIsoString()));
     }
     else
     {
         var strValue = JSONObject.Stringify(this.Engine, value, null, null);
         m_excelWorksheet.SetValue(address, strValue);
     }
 }
Esempio n. 23
0
        public SPFileInstance AddFile(string url, object data, object overwrite)
        {
            bool bOverwrite = false;

            byte[] byteData;

            if (String.IsNullOrEmpty(url))
            {
                throw new JavaScriptException(Engine, "Error", "A url of the new file must be specified.");
            }

            if (data == Null.Value || data == Undefined.Value || data == null)
            {
                throw new JavaScriptException(Engine, "Error", "Data must be specified.");
            }

            var instance = data as Base64EncodedByteArrayInstance;

            if (instance != null)
            {
                byteData = instance.Data;
            }
            else if (data is ObjectInstance)
            {
                byteData = Encoding.UTF8.GetBytes(JSONObject.Stringify(Engine, data, null, null));
            }
            else
            {
                byteData = Encoding.UTF8.GetBytes(JSONObject.Stringify(Engine, data.ToString(), null, null));
            }

            if (overwrite != Null.Value && overwrite != Undefined.Value && overwrite != null)
            {
                if (overwrite is Boolean)
                {
                    bOverwrite = (bool)overwrite;
                }
                else
                {
                    bOverwrite = Boolean.Parse(overwrite.ToString());
                }
            }

            var file = m_list.RootFolder.Files.Add(url, byteData, bOverwrite);

            return(new SPFileInstance(Engine.Object.InstancePrototype, file));
        }
        public void Log(FirebugConsoleMessageStyle style, object[] objects)
        {
            var baristaLogService = new BaristaDiagnosticsService(BaristaDiagnosticsService.DiagnosticsAreaName, SPFarm.Local);

            var cat = baristaLogService[BaristaDiagnosticCategory.Console];

            var output = new StringBuilder();

            for (var i = 0; i < objects.Length; i++)
            {
                if (i > 0)
                {
                    output.AppendLine();
                }
                if (objects[i] is ObjectInstance)
                {
                    output.AppendLine(JSONObject.Stringify(this.Engine, objects[i], null, null));
                }
                else
                {
                    output.AppendLine(TypeConverter.ToString(objects[i]));
                }
            }

            var severity = TraceSeverity.None;

            switch (style)
            {
            case FirebugConsoleMessageStyle.Error:
                severity = TraceSeverity.Unexpected;
                break;

            case FirebugConsoleMessageStyle.Information:
                severity = TraceSeverity.Verbose;
                break;

            case FirebugConsoleMessageStyle.Regular:
                severity = TraceSeverity.Medium;
                break;

            case FirebugConsoleMessageStyle.Warning:
                severity = TraceSeverity.Monitorable;
                break;
            }

            baristaLogService.WriteTrace(1, cat, severity, output.ToString(), baristaLogService.TypeName);
        }
Esempio n. 25
0
        public SPFileInstance Write(string fileUrl, object contents)
        {
            byte[] data;
            if (contents is Base64EncodedByteArrayInstance)
            {
                data = (contents as Base64EncodedByteArrayInstance).Data;
            }
            else if (contents is StringInstance || contents is string)
            {
                data = Encoding.UTF8.GetBytes((string)contents);
            }
            else if (contents is ObjectInstance)
            {
                data = Encoding.UTF8.GetBytes(JSONObject.Stringify(Engine, contents, null, null));
            }
            else
            {
                data = Encoding.UTF8.GetBytes(contents.ToString());
            }

            if (Uri.IsWellFormedUriString(fileUrl, UriKind.Relative))
            {
                fileUrl = SPUtility.ConcatUrls(m_site.Url, fileUrl);
            }

            SPFile result;

            if (SPHelper.TryGetSPFile(fileUrl, out result))
            {
                SPWeb web;
                if (SPHelper.TryGetSPWeb(fileUrl, out web))
                {
                    result = web.Files.Add(fileUrl, data);
                }
                else
                {
                    throw new JavaScriptException(Engine, "Error", "Could not locate the specified web:  " + fileUrl);
                }
            }
            else
            {
                result.SaveBinary(data);
            }

            return(new SPFileInstance(Engine.Object.InstancePrototype, result));
        }
        public void AddItemToCache(string cacheKey, object item, object absoluteExpiration, object slidingExpiration)
        {
            string stringItem;
            var    dtExpiration = Cache.NoAbsoluteExpiration;
            var    tsExpiration = Cache.NoSlidingExpiration;

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

            if (item is ObjectInstance)
            {
                stringItem = JSONObject.Stringify(Engine, item, null, null);
            }
            else
            {
                stringItem = item.ToString();
            }

            if (absoluteExpiration != Null.Value && absoluteExpiration != Undefined.Value && absoluteExpiration != null)
            {
                if (absoluteExpiration is DateInstance)
                {
                    dtExpiration = DateTime.Parse((absoluteExpiration as DateInstance).ToIsoString());
                }
                else
                {
                    dtExpiration = DateTime.Parse(absoluteExpiration.ToString());
                }
            }

            if (slidingExpiration != Null.Value && slidingExpiration != Undefined.Value && slidingExpiration != null)
            {
                if (slidingExpiration is DateInstance)
                {
                    tsExpiration = TimeSpan.FromMilliseconds((slidingExpiration as DateInstance).ValueInMilliseconds);
                }
                else
                {
                    tsExpiration = TimeSpan.Parse(slidingExpiration.ToString());
                }
            }

            HttpRuntime.Cache.Insert(cacheKey, stringItem, null, dtExpiration, tsExpiration);
        }
        public void AddObjectToIndex(object obj)
        {
            //TODO: if the obj is a SPListItemInstance, create a document from the list item.
            var objString   = JSONObject.Stringify(this.Engine, obj, null, null);
            var objectToAdd = JObject.Parse(objString);

            var doc = LuceneHelper.ConvertObjectToDocument(objectToAdd);

            try
            {
                m_indexWriter.AddDocument(doc);
            }
            catch (OutOfMemoryException)
            {
                LuceneHelper.CloseIndexWriterSingleton(m_targetFolder);
            }
        }
Esempio n. 28
0
        public string Json2Xml(object jsonObject)
        {
            string text;

            if (jsonObject is ObjectInstance)
            {
                text = JSONObject.Stringify(this.Engine, jsonObject, null, null);
            }
            else
            {
                text = jsonObject as string;
            }

            var document = JsonConvert.DeserializeXmlNode(text);

            return(document.OuterXml);
        }
        public void SetWorkbookRaw(object jsonObject)
        {
            string text;

            if (jsonObject is ObjectInstance)
            {
                text = JSONObject.Stringify(this.Engine, jsonObject, null, null);
            }
            else
            {
                text = jsonObject as string;
            }

            var document = JsonConvert.DeserializeXmlNode(text);

            m_excelWorkbook.WorkbookXml.LoadXml(document.OuterXml);
        }
Esempio n. 30
0
        public void Log(FirebugConsoleMessageStyle style, object[] objects)
        {
            var logger = LogManager.GetCurrentClassLogger();

            var output = new StringBuilder();

            for (var i = 0; i < objects.Length; i++)
            {
                if (i > 0)
                {
                    output.AppendLine();
                }
                if (objects[i] is ObjectInstance)
                {
                    output.AppendLine(JSONObject.Stringify(this.Engine, objects[i], null, null));
                }
                else
                {
                    output.AppendLine(TypeConverter.ToString(objects[i]));
                }
            }

            var severity = LogLevel.Trace;

            switch (style)
            {
            case FirebugConsoleMessageStyle.Error:
                severity = LogLevel.Error;
                break;

            case FirebugConsoleMessageStyle.Information:
                severity = LogLevel.Information;
                break;

            case FirebugConsoleMessageStyle.Regular:
                severity = LogLevel.Debug;
                break;

            case FirebugConsoleMessageStyle.Warning:
                severity = LogLevel.Warning;
                break;
            }

            logger.Log(severity, output.ToString);
        }