Ejemplo n.º 1
0
        private static IEnumerable <JsonError> Validate(string instanceText, string schemaText)
        {
            List <JsonError> errors = new List <JsonError>();

            JSONDocument instanceDocument = JSONParser.Parse(instanceText);

            AddSyntaxErrors(instanceDocument, JsonErrorLocation.InstanceDocument, errors);

            JSONDocument schemaDocument = JSONParser.Parse(schemaText);

            AddSyntaxErrors(schemaDocument, JsonErrorLocation.Schema, errors);

            var loader = new JSONDocumentLoader();

            loader.SetCacheItem(new JSONDocumentLoadResult(instanceDocument));
            loader.SetCacheItem(new JSONDocumentLoadResult(schemaDocument));

            JSONSchemaDraft4EvaluationTreeNode tree =
                JSONSchemaDraft4EvaluationTreeProducer.CreateEvaluationTreeAsync(
                    instanceDocument,
                    (JSONObject)schemaDocument.TopLevelValue,
                    loader,
                    Enumerable.Empty <IJSONSchemaFormatHandler>()).Result;

            AddValidationErrors(tree.ValidationIssues, errors);

            return(errors);
        }
Ejemplo n.º 2
0
        public void TestCreate()
        {
            // create a document and root
            var doc = JSONDocument.CreateDocument();

            doc.Root = doc.CreateItemObject();

            // add some items to root: use explicit creation of items
            doc.RootAsObject.Add("FirstName", doc.CreateItemString("Hans"));
            doc.RootAsObject.Add("LastName", doc.CreateItemString("Wurst"));
            doc.RootAsObject.Add("age", doc.CreateItemNumber(42));

            // create and add an object and fill, use implicit creation of items
            var address = doc.CreateItemObject();

            address.Add("street", "infinite loop 0");
            address.Add("city", "Duckburg");
            doc.RootAsObject.Add("Address", address);

            // create and add an array
            var childAge = doc.CreateItemArray();

            childAge.Add(3);
            childAge.Add(10);
            childAge.Add(12);
            doc.RootAsObject.Add("AgeOfChildren", childAge);

            Assert.NotNull(doc.Root);
            Assert.NotNull(doc.RootAsObject["FirstName"] as IJSONItemString);

            Assert.True(((IJSONItemString)doc.RootAsObject["FirstName"]).Value != null);
        }
Ejemplo n.º 3
0
        internal List<FailedDocument> DeleteDocuments(ICollection<string> documentKeys, bool noResponse)
        {
           
            List<JSONDocument> documents = new List<JSONDocument>();
            foreach (string documentKey in documentKeys)
            {
                if (documentKey != null)
                {
                    JSONDocument jdoc = new JSONDocument();
                    jdoc.Key = documentKey;
                    documents.Add(jdoc);
                }
                //else
                //    throw new ArgumentException("Document key cannot be an empty string or null");
            }

            DeleteDocumentsOperation deleteDocumentsOperation = new DeleteDocumentsOperation();
            deleteDocumentsOperation.Documents = documents.Cast<IJSONDocument>().ToList();
            deleteDocumentsOperation.Database = _database.DatabaseName;
            deleteDocumentsOperation.Collection = _collectionName;
            deleteDocumentsOperation.NoResponse = noResponse;

            DeleteDocumentsResponse deleteDocumentsResponse = (DeleteDocumentsResponse)_database.ExecutionMapper.DeleteDocuments(deleteDocumentsOperation);

            if (!deleteDocumentsResponse.IsSuccessfull)
            {
                if (deleteDocumentsResponse.FailedDocumentsList == null || deleteDocumentsResponse.FailedDocumentsList.Count == 0)
                {
                    throw new DataException(ErrorMessages.GetErrorMessage(deleteDocumentsResponse.ErrorCode, deleteDocumentsResponse.ErrorParams));
                }
                return deleteDocumentsResponse.FailedDocumentsList;
            }
            return new List<FailedDocument>();
        }
Ejemplo n.º 4
0
        /// <summary>
        /// This is a temporaray method should be removed
        /// </summary>
        /// <param name="_currentBucket"></param>
        /// <param name="keys"></param>
        private void InsertKeysToCollection(int _currentBucket, ICollection keys)
        {
            if (keys != null && keys.Count > 0)
            {
                IEnumerator          keysEnum  = keys.GetEnumerator();
                LocalInsertOperation operation = new LocalInsertOperation();
                operation.Database   = Common.MiscUtil.SYSTEM_DATABASE;
                operation.Collection = this.bucketKeysColName;
                operation.Documents  = new ClusteredList <IJSONDocument>();

                while (keysEnum.MoveNext())
                {
                    try
                    {
                        StateTransferKey key = new StateTransferKey(_currentBucket, keysEnum.Current as DocumentKey);

                        JSONDocument stateTransferKeyDoc = JsonSerializer.Serialize <StateTransferKey>(key);
                        operation.Documents.Add(stateTransferKeyDoc);
                    }
                    catch (Exception ex)
                    {
                        //log exception
                    }
                }
                if (_databasesManager != null)
                {
                    _databasesManager.InsertDocuments(operation);
                }
            }
        }
Ejemplo n.º 5
0
        public ICollectionReader GetDocuments(ICollection<string> documentKeys)
        {
            if (documentKeys == null)
                throw new ArgumentNullException("documentKeys");
            if (documentKeys.Count < 1)
                throw new ArgumentException("No DocumentKey specified");

            List<JSONDocument> documents = new List<JSONDocument>();
            foreach (string documentKey in documentKeys)
            {
                if (documentKey != null)
                {
                    JSONDocument jdoc = new JSONDocument();
                    jdoc.Key = documentKey;
                    documents.Add(jdoc);
                }
            }

            GetDocumentsOperation getDocumentsOperation = new GetDocumentsOperation();

            getDocumentsOperation.DocumentIds = documents.Cast<IJSONDocument>().ToList();
            getDocumentsOperation.Database = _database.DatabaseName;
            getDocumentsOperation.Collection = _collectionName;

            GetDocumentsResponse getDocumentsResponse = (GetDocumentsResponse)_database.ExecutionMapper.GetDocuments(getDocumentsOperation);

            if (getDocumentsResponse.IsSuccessfull)
            {
                CollectionReader reader = new CollectionReader((DataChunk)getDocumentsResponse.DataChunk, _database.ExecutionMapper, _database.DatabaseName, _collectionName);
                return reader;
            }
            else
                throw new Exception("Operation failed Error: " + Common.ErrorHandling.ErrorMessages.GetErrorMessage(getDocumentsResponse.ErrorCode, getDocumentsResponse.ErrorParams));
        }
Ejemplo n.º 6
0
        private string GetResponseBody(HttpWebResponse response)
        {
            //Get Response Body.
            string responseJson = string.Empty;
            Stream dataStream   = response.GetResponseStream();

            if (dataStream != null)
            {
                var    reader             = new StreamReader(dataStream);
                string responseFromServer = reader.ReadToEnd();

                //Response Body will be in JSON Form.
                IJSONDocument responseDocument = JSONDocument.Parse(responseFromServer);
                if (responseDocument != null && responseDocument.Contains("value"))
                {
                    responseJson = responseDocument.GetString("value");  //Data will be in value
                }
                reader.Close();
            }
            if (dataStream != null)
            {
                dataStream.Close();
            }
            return(responseJson);
        }
Ejemplo n.º 7
0
        public static List <JSONDocument> Serialize <T>(List <T> documents)
        {
            if (typeof(T) == typeof(JSONDocument))
            {
                return(documents as List <JSONDocument>);
            }

            List <JSONDocument> JSONDocuments;

            JSONDocuments = new List <JSONDocument>();
            JSONDocument jdoc;

            foreach (T document in documents)
            {
                if (document != null)
                {
                    string str = JsonConvert.SerializeObject(document);
                    jdoc = (JSONDocument)JSONDocument.Parse(str);
                    JSONDocuments.Add(jdoc);
                }
                else
                {
                    throw new ArgumentException("document cannot be null");
                }
            }
            return(JSONDocuments);
        }
Ejemplo n.º 8
0
        public static JSONResult ToJSONResult(JSONDocument document)
        {
            JSONResult result = new JSONResult();

            result.Key     = document.Key;
            result._values = document.ToDictionary();
            return(result);
        }
Ejemplo n.º 9
0
        public void TestWrite()
        {
            var doc = JSONDocument.CreateDocument();

            doc.Root = doc.CreateItemNumber(42);
            var json = JSONWriter.CreateUnformattedWriter().WriteToString(doc);

            Assert.True(json.IndexOf("42") >= 0);
        }
Ejemplo n.º 10
0
 private void Parse(JSONDocument jsonDoc)
 {
     TargetPath = jsonDoc.Root.AsDictionary()["TargetPath"].AsString();
     SourcePath = jsonDoc.Root.AsDictionary()["SourcePath"].AsString();
     foreach (var mod in jsonDoc.Root.AsDictionary()["Mods"].AsDictionary())
     {
         Mods[(EncryptCompressMode)Enum.Parse(typeof(EncryptCompressMode), mod.Key)] = mod.Value.AsString();
     }
     IsParsed = true;
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Converts data into JSON for computer graphics
        /// </summary>
        public void ToJSON()
        {
            IJSONDocument  doc = JSONDocument.CreateDocument();
            IJSONItemArray arr = doc.CreateItemArray();

            foreach (Beam b in this.GetAllProperties())
            {
                IJSONItem o = b.ToJSON(doc);
                arr.Add(o);
            }
        }
Ejemplo n.º 12
0
        //private JsonSerializerSettings _settings = new JsonSerializerSettings();
        //public JsonSerializer()
        //{
        //    _settings.TypeNameHandling = TypeNameHandling.Objects;
        //}

        public static JSONDocument Serialize <T>(T document)
        {
            if (document == null)
            {
                return(null);
            }
            if (typeof(T) == typeof(JSONDocument))
            {
                return((JSONDocument)(object)document);
            }
            return((JSONDocument)JSONDocument.Parse(JsonConvert.SerializeObject(document)));
        }
Ejemplo n.º 13
0
        public DeleteDocumentsOperation(Alachisoft.NosDB.Common.Protobuf.Command command) : base(command.ToBuilder())
        {
            _deleteCommand = command.DeleteDocumentsCommand.ToBuilder();
            _documentIds   = new List <IJSONDocument>();

            foreach (string document in _deleteCommand.DocumentIdsList)
            {
                _documentIds.Add(JSONDocument.Parse(document));
            }

            base.Message = this;
        }
Ejemplo n.º 14
0
        public static IJSONDocument Serialize(object document)
        {
            var serialize = document as IJSONDocument;

            if (serialize != null)
            {
                return(serialize);
            }

            string str = JsonConvert.SerializeObject(document);

            return(JSONDocument.Parse(str));
        }
Ejemplo n.º 15
0
        public static IList <IParameter> GetParameterList(IList <Protobuf.Parameter> paramList)
        {
            IList <IParameter> parameterList = new List <IParameter>();

            foreach (Protobuf.Parameter param in paramList)
            {
                try
                {
                    switch ((ParameterType)param.JsonDataType)
                    {
                    case ParameterType.NULL:
                        parameterList.Add(new Parameter(param.Attribute, null));
                        break;

                    case ParameterType.BOOLEAN:
                        parameterList.Add(new Parameter(param.Attribute, bool.Parse(param.Value)));
                        break;

                    case ParameterType.DATETIME:
                        parameterList.Add(new Parameter(param.Attribute, DateTime.Parse(param.Value)));
                        break;

                    case ParameterType.STRING:
                        parameterList.Add(new Parameter(param.Attribute, param.Value));
                        break;

                    case ParameterType.LONG:
                        parameterList.Add(new Parameter(param.Attribute, long.Parse(param.Value)));
                        break;

                    case ParameterType.DOUBLE:
                        parameterList.Add(new Parameter(param.Attribute, double.Parse(param.Value)));
                        break;

                    case ParameterType.ARRAY:
                        parameterList.Add(new Parameter(param.Attribute,
                                                        Alachisoft.NosDB.Common.JSON.JsonDocumentUtil.ParseArray(JsonConvert.DeserializeObject <JArray>(param.Value))));
                        break;

                    default:
                        parameterList.Add(new Parameter(param.Attribute, JSONDocument.Parse(param.Value)));
                        break;
                    }
                }
                catch (NotSupportedException ex)
                {
                    throw new QuerySystemException(ErrorCodes.Query.PARAMETER_NOT_SUPPORTED, new[] { param.Attribute, ex.Message });
                }
            }
            return(parameterList);
        }
Ejemplo n.º 16
0
        private JSONDocument CreateJSONDocument(IDictionary <int, string> header, IDictionary <int, object> value)
        {
            JSONDocument document   = null;
            int          pos        = 0;
            var          jsonString = new StringBuilder();

            // append starting brace
            jsonString.Append(@"{");

            foreach (KeyValuePair <int, string> kvp in header)
            {
                //key tag
                jsonString.Append('\"' + kvp.Value + '\"' + ":");

                object   val  = value[kvp.Key].ToString();
                DataType type = GetDataType(val.ToString());

                if (header[pos].Equals(_key))
                {
                    jsonString.Append('\"' + val.ToString() + '\"');
                }
                else
                {
                    if (type == DataType.STRING || type == DataType.DATETIME)
                    {
                        jsonString.Append('\"' + val.ToString() + '\"');
                    }
                    else if (type == DataType.SYSTEM_NULL)
                    {
                        // append null in place of any nullable value
                        jsonString.Append("null");
                    }
                    else
                    {
                        jsonString.Append(val.ToString());
                    }
                }

                if (pos < value.Count)
                {
                    jsonString.Append(',');
                }
                pos++;
            }

            // append ending brace
            jsonString.Append(@"}");
            document = JsonConvert.DeserializeObject <JSONDocument>(jsonString.ToString());
            return(document);
        }
Ejemplo n.º 17
0
        private JSONDocument DeserializeDocument(byte[] data)
        {
            var stream = new ClusteredMemoryStream(data);
            int header = stream.ReadByte();

            if ((header & (long)PersistenceBits.Compressed) == (decimal)PersistenceBits.Compressed)
            {
                stream = CompressionUtil.Decompress(stream);
            }
            var document = JSONDocument.Deserialize(stream);// CompactBinaryFormatter.Deserialize(stream, string.Empty);

            stream.Dispose();
            return(document as JSONDocument);
        }
Ejemplo n.º 18
0
 private static void AddSyntaxErrors(JSONDocument document, JsonErrorLocation location, List <JsonError> errors)
 {
     foreach (Tuple <JSONParseItem, JSONParseError> parserError in document.GetContainedParseErrors())
     {
         errors.Add(new JsonError
         {
             Kind     = JsonErrorKind.Syntax,
             Start    = parserError.Item1.Start,
             Length   = parserError.Item1.Length,
             Location = location,
             Message  = parserError.Item2.Text ?? parserError.Item2.ErrorType.ToString()
         });
     }
 }
        public override IEnumerable<string> GetIssues(JSONDocument doc, string canonicalizedValue)
        {
            if (string.IsNullOrEmpty(doc.DocumentLocation) || canonicalizedValue.Contains("*"))
                yield break;

            string fileName = Path.GetFileName(doc.DocumentLocation);

            if (!fileName.Equals(Constants.CONFIG_FILENAME, StringComparison.OrdinalIgnoreCase))
                yield break;

            string folder = Path.GetDirectoryName(doc.DocumentLocation);
            string absolutePath = Path.Combine(folder, canonicalizedValue).Replace("!", string.Empty);

            if (!File.Exists(absolutePath) && !Directory.Exists(absolutePath))
                yield return $"The file or directory '{canonicalizedValue}' does not exist";
        }
 public BowerNameCompletionEntry(string text, IIntellisenseSession session, DTE2 dte, JSONDocument doc)
     : base(text, "\"" + text + "\"", null, Constants.Icon, null, false, session as ICompletionSession)
 {
     _dte = dte;
     _doc = doc;
 }