Пример #1
0
        public JsonValue getProp(string name, JsonTypes type)
        {
            var value = getProp(name);

            Root.instance.logging.assert(value.Type == type, "property type mismatch");
            return(value);
        }
Пример #2
0
        public static IJType GetJsonDecoded(Context context, byte[] message, long senderId)
        {
            byte[] aesBinKey = context.Contacts
                               .Where(u => u.PublicId == senderId)
                               .Select(u => u.ReceiveAesKey)
                               .SingleOrDefault();

            AESPassword key = new AESPassword(aesBinKey);

            byte[]    decrypted = key.Decrypt(message);
            JsonTypes type      = (JsonTypes)decrypted[0];
            string    jsonText  = Encoding.UTF8.GetString(decrypted, 1, decrypted.Length - 1);

            switch (type)
            {
            case JsonTypes.ALARM:
                return(JsonConvert.DeserializeObject <JAlarm>(jsonText));

            case JsonTypes.CONTACT_DETAIL:
                return(JsonConvert.DeserializeObject <JContactDetail>(jsonText));

            case JsonTypes.MESSAGES:
                return(JsonConvert.DeserializeObject <JMessage>(jsonText));

            case JsonTypes.MESSAGES_THREAD:
                return(JsonConvert.DeserializeObject <JMessageThread>(jsonText));

            case JsonTypes.AES_KEY:
                return(JsonConvert.DeserializeObject <JAESKey>(jsonText));

            default:
                throw new Exception("Unknown JsonType.");
            }
        }
Пример #3
0
        public static JsonCapsula GetJsonDecoded(Context context, byte[] message, long senderId)
        {
            byte[] aesBinKey = context.Contacts
                               .Where(u => u.PublicId == senderId)
                               .Select(u => u.ReceiveAesKey)
                               .SingleOrDefault();

            AESPassword key = new AESPassword(aesBinKey);

            byte[] decrypted = key.Decrypt(message);

            MemoryStream stream   = new MemoryStream(decrypted);
            JsonTypes    type     = (JsonTypes)BinaryEncoder.ReadInt(stream);
            string       jsonText = TextEncoder.ReadString(stream);

            byte[] attechment   = null;
            int    isAttechment = BinaryEncoder.ReadInt(stream);

            if (isAttechment == 1)
            {
                attechment = BinaryEncoder.ReceiveBytes(stream);
            }

            IJType jmessage;

            switch (type)
            {
            case JsonTypes.ALARM:
                jmessage = JsonConvert.DeserializeObject <JAlarm>(jsonText);
                break;

            case JsonTypes.CONTACT:
                jmessage = JsonConvert.DeserializeObject <JContact>(jsonText);
                break;

            case JsonTypes.MESSAGES:
                jmessage = JsonConvert.DeserializeObject <JMessage>(jsonText);
                break;

            case JsonTypes.MESSAGES_THREAD:
                jmessage = JsonConvert.DeserializeObject <JMessageThread>(jsonText);
                break;

            default:
                throw new Exception("Unknown JsonType.");
            }

            return(new JsonCapsula()
            {
                Attechment = attechment,
                Message = jmessage
            });
        }
Пример #4
0
        /// <summary>
        /// Parses json string and returns a dictionary with kay value pairs
        /// </summary>
        /// <param name="json">Json string to be parsed</param>
        /// <returns>Dictionary containing all key value pairs</returns>
        public Dictionary <string, object> Deserialize(string json)
        {
            #region Validation

            if (json == null)
            {
                ThrowError(INVALID_JSON_MSG);
            }

            #endregion

            Dictionary <string, object> dict = new Dictionary <string, object>();

            json = json.Trim();

            #region Validation

            if (json.Length == 0 || json[0] != '{')
            {
                ThrowError(INVALID_JSON_MSG);
            }

            #endregion

            json = json.Remove(0, 1); //Removing first {

            while (json.Trim() != string.Empty)
            {
                JsonTypes nextDataType = GetNextDataType(json);

                switch (nextDataType)
                {
                case JsonTypes.KEY_VALUE:
                    SetKeyValue(ref json, dict);
                    break;

                case JsonTypes.KEY_ARRAY:
                    SetKeyArray(ref json, dict);
                    break;

                case JsonTypes.KEY_OBJECT:
                    SetKeyObject(ref json, dict);
                    break;
                }
            }

            return(dict);
        }
Пример #5
0
        protected string GetCSharpType(JsonTypes jsonType, bool optional, PropertyDescriptor arrayType)
        {
            switch (jsonType)
            {
            case JsonTypes.Any:
            case JsonTypes.Object:
                return("object");

            case JsonTypes.Boolean:
                return(optional ? "bool?" : "bool");

            case JsonTypes.Integer:
                return(optional ? "long?" : "long");

            case JsonTypes.Number:
                return(optional ? "double?" : "double");

            case JsonTypes.String:
                return("string");

            case JsonTypes.Array:
                if (arrayType == null)
                {
                    return("Array");
                }
                else if (arrayType.TypeReference != null)
                {
                    return(arrayType.TypeReference + "[]");
                }
                else if (arrayType.Type != null)
                {
                    return(GetCSharpType(arrayType.Type.Value, arrayType.Optional, arrayType.ArrayType) + "[]");
                }
                else
                {
                    throw new NotImplementedException();
                }

            default:
                throw new UnreachableCodeReachedException();
            }
        }
Пример #6
0
 private JsonAttributeScanningWalker(Compilation compilation, SyntaxWalkerDepth depth = SyntaxWalkerDepth.Node) : base(depth)
 {
     Compilation = compilation;
     JsonTypes.Add(TypeName.String, new JsonType(TypeName.String, _ => "reader.GetString()", (_, valueExpr) => $"writer.WriteStringValue({valueExpr});", null, null, null, null));
     JsonTypes.Add(TypeName.Bool, new JsonType(TypeName.Bool, _ => "reader.GetBoolean()", (_, valueExpr) => $"writer.WriteBooleanValue({valueExpr});", null, null, null, null));
     JsonTypes.Add(TypeName.Byte, new JsonType(TypeName.Byte, _ => "reader.GetByte()", (_, valueExpr) => $"writer.WriteNumberValue({valueExpr});", null, null, null, null));
     JsonTypes.Add(TypeName.SByte, new JsonType(TypeName.SByte, _ => "reader.GetSByte()", (_, valueExpr) => $"writer.WriteNumberValue({valueExpr});", null, null, null, null));
     JsonTypes.Add(TypeName.Int16, new JsonType(TypeName.Int16, _ => "reader.GetInt16()", (_, valueExpr) => $"writer.WriteNumberValue({valueExpr});", null, null, null, null));
     JsonTypes.Add(TypeName.Int32, new JsonType(TypeName.Int32, _ => "reader.GetInt32()", (_, valueExpr) => $"writer.WriteNumberValue({valueExpr});", null, null, null, null));
     JsonTypes.Add(TypeName.Int64, new JsonType(TypeName.Int64, _ => "reader.GetInt64()", (_, valueExpr) => $"writer.WriteNumberValue({valueExpr});", null, null, null, null));
     JsonTypes.Add(TypeName.UInt16, new JsonType(TypeName.UInt16, _ => "reader.GetUInt16()", (_, valueExpr) => $"writer.WriteNumberValue({valueExpr});", null, null, null, null));
     JsonTypes.Add(TypeName.UInt32, new JsonType(TypeName.UInt32, _ => "reader.GetUInt32()", (_, valueExpr) => $"writer.WriteNumberValue({valueExpr});", null, null, null, null));
     JsonTypes.Add(TypeName.UInt64, new JsonType(TypeName.UInt64, _ => "reader.GetUInt64()", (_, valueExpr) => $"writer.WriteNumberValue({valueExpr});", null, null, null, null));
     JsonTypes.Add(TypeName.Single, new JsonType(TypeName.Single, _ => "reader.GetSingle()", (_, valueExpr) => $"writer.WriteNumberValue({valueExpr});", null, null, null, null));
     JsonTypes.Add(TypeName.Double, new JsonType(TypeName.Double, _ => "reader.GetDouble()", (_, valueExpr) => $"writer.WriteNumberValue({valueExpr});", null, null, null, null));
     JsonTypes.Add(TypeName.Decimal, new JsonType(TypeName.Decimal, _ => "reader.GetDecimal()", (_, valueExpr) => $"writer.WriteNumberValue({valueExpr});", null, null, null, null));
     JsonTypes.Add(TypeName.DateTime, new JsonType(TypeName.DateTime, _ => "reader.GetDateTime()", (_, valueExpr) => $"JsonSerializer.Serialize<DateTime>(writer, {valueExpr}, options);", null, null, null, null));
     JsonTypes.Add(TypeName.DateTimeOffset, new JsonType(TypeName.DateTimeOffset, _ => "reader.GetDateTimeOffset()", (_, valueExpr) => $"JsonSerializer.Serialize<DateTimeOffset>({valueExpr});", null, null, null, null));
     JsonTypes.Add(TypeName.Guid, new JsonType(TypeName.Guid, _ => "reader.GetGuid()", (_, valueExpr) => $"JsonSerializer.Serialize<Guid>({valueExpr});", null, null, null, null));
 }
Пример #7
0
    private void ExtractData(JsonTypes jType, string data)
    {
        switch (jType)
        {
        case JsonTypes.Command:
            break;

        case JsonTypes.MediaPlan:
            break;

        case JsonTypes.MediaTemplate:
            break;

        case JsonTypes.Message:
            var msg = JsonUtility.FromJson <Message>(data);
            _sender.Append(msg.Name);
            _msg.Append(msg.Text);
            break;
        }
    }
Пример #8
0
        public static AntModel GetJsonData(JsonTypes jsonType, string url = "")
        {
            switch (jsonType)
            {
            case JsonTypes.TEST:
                return(JsonConvert.DeserializeObject <AntModel>(new TestJsonWorker().GetJsonFile(url)));

            case JsonTypes.API_QUADIENT:
                url = "http://tasks-rad.quadient.com:8080/task";
                return(JsonConvert.DeserializeObject <AntModel>(new ReceiveJsonWorker().GetJsonFile(url)));

            case JsonTypes.URL:
                return(JsonConvert.DeserializeObject <AntModel>(new ReceiveJsonWorker().GetJsonFile(url)));

            case JsonTypes.FILE:
                return(JsonConvert.DeserializeObject <AntModel>(new ReceiveJsonFile().GetJsonFile(url)));

            default:
                throw new Exception("Unknown source of JSON file");
            }
        }
Пример #9
0
        /// <summary>
        /// Gets the type of data present in the next sequence
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private JsonTypes GetNextDataType(string data)
        {
            JsonTypes type = JsonTypes.KEY_VALUE;

            string tempData   = data;
            int    colonIndex = IndexOfJsonSpecialChar(data, ':', '\0');

            if (colonIndex == -1)
            {
                ThrowError(INVALID_JSON_MSG);
            }

            tempData = tempData.Remove(0, colonIndex + 1).Trim();

            if (tempData.Length > 1)
            {
                char valueFirstChar = tempData[0];

                if (valueFirstChar == '{')
                {
                    type = JsonTypes.KEY_OBJECT;
                }
                else if (valueFirstChar == '[')
                {
                    type = JsonTypes.KEY_ARRAY;
                }
                else
                {
                    type = JsonTypes.KEY_VALUE;
                }
            }
            else
            {
                ThrowError(INVALID_JSON_MSG);
            }

            return(type);
        }
Пример #10
0
        public static ResponseAntModel SendJsonResponse(JsonTypes jsonType, string id, string path, string url = "")
        {
            switch (jsonType)
            {
            case JsonTypes.TEST:
                return(new ResponseAntModel
                {
                    InTime = true,
                    Valid = (path == "DLDRRU"),
                    Message = (path == "DLDRRU" ? "Test OK" : "Test Failed")
                });

            case JsonTypes.API_QUADIENT:
                url = string.Format("http://tasks-rad.quadient.com:8080/task/{0}", id);
                return(new SendJsonWorker().SendJsonFile(url, path));

            case JsonTypes.URL:
                url = string.Format(url + "/" + id);
                return(new SendJsonWorker().SendJsonFile(url, path));

            default:
                throw new Exception("Unknown url for JSON reponse");
            }
        }
Пример #11
0
        public static void RunAntQuest(JsonTypes jsonWorker, PathAlgorithms pathAlgorithm, bool DEBUG, string url = "")
        {
            try
            {
                var sw = new Stopwatch();
                sw.Start();

                Console.WriteLine("Running ANT QUEST for {0} and {1}", jsonWorker, pathAlgorithm);

                AntModel antModel = JsonSimpleFactory.GetJsonData(jsonWorker, url);
                if (DEBUG)
                {
                    Console.WriteLine("Obtaining data took: {0} ms", sw.Elapsed.Milliseconds);
                }

                sw.Restart();

                var antGraph = new Graph(antModel);
                if (DEBUG)
                {
                    Console.WriteLine("Graph preparation took: {0} ms", sw.Elapsed.Milliseconds);
                }

                sw.Restart();

                var pathFinder = PathFinderFactory.PathFactory(antGraph, pathAlgorithm);
                var path       = pathFinder.FindPath();
                var pathString = pathFinder.GetPathSimpleString(path);

                if (DEBUG)
                {
                    Console.WriteLine("Path finding took: {0} ms", sw.Elapsed.Milliseconds);
                }
                if (DEBUG)
                {
                    Console.WriteLine("Final path is: {0}", pathString);
                }

                sw.Restart();

                if (jsonWorker == JsonTypes.TEST || jsonWorker == JsonTypes.URL || jsonWorker == JsonTypes.API_QUADIENT)
                {
                    var serverResponse =
                        JsonSimpleFactory.SendJsonResponse(jsonWorker, antGraph.ID, pathString, url);
                    Console.WriteLine(serverResponse.Message);

                    if (serverResponse.Valid && serverResponse.InTime && DEBUG)
                    {
                        Console.WriteLine("Test passed");
                    }
                    else if (DEBUG)
                    {
                        Console.WriteLine("Test failed");
                    }
                }

                if (DEBUG)
                {
                    Console.WriteLine("Sending data took: {0} ms", sw.Elapsed.Milliseconds);
                }

                sw.Stop();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Пример #12
0
        private void ok_Click(object sender, EventArgs e)
        {
            try {
                // Salva tutti i dettagli nel model

                if (inutColumnCb.SelectedIndex == -1)
                {
                    MessageBox.Show("No input column has been selected. If none is available, please attach an input with textual columns to this component.");
                    return;
                }
                else
                {
                    _model.InputColumnName = inutColumnCb.SelectedItem.ToString();
                }

                _model.ClearMapping();
                // - Salva le impostazioni di IO
                if (uiIOGrid.IsCurrentCellDirty || uiIOGrid.IsCurrentRowDirty)
                {
                    uiIOGrid.CurrentRow.DataGridView.EndEdit();
                    uiIOGrid.EndEdit();
                    CurrencyManager cm = (CurrencyManager)uiIOGrid.BindingContext[uiIOGrid.DataSource, uiIOGrid.DataMember];
                    cm.EndCurrentEdit();
                }

                int row = 1;
                foreach (DataGridViewRow r in uiIOGrid.Rows)
                {
                    if (r.IsNewRow)
                    {
                        continue;
                    }
                    string inputName = null;
                    try {
                        inputName = (string)r.Cells[0].Value;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("JSON Field Name on row " + row);
                        return;
                    }
                    int maxLen = -1;
                    try
                    {
                        maxLen = int.Parse((string)r.Cells[1].Value.ToString());
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Maximum length is invalid on row " + row);
                        return;
                    }

                    string outName = null;
                    try
                    {
                        outName = (string)r.Cells[2].Value;
                        if (string.IsNullOrEmpty(outName))
                        {
                            throw new ArgumentException();
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Output Column name is invalid on row " + row);
                        return;
                    }

                    JsonTypes dataType = 0;
                    try
                    {
                        dataType = (JsonTypes)Enum.Parse(typeof(JsonTypes), (string)r.Cells[3].Value);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Column type is invalid on row " + row);
                        return;
                    }

                    IOMapEntry map = new IOMapEntry();
                    map.InputFieldPath       = inputName;
                    map.OutputColName        = outName;
                    map.OutputJsonColumnType = dataType;
                    map.InputFieldLen        = maxLen;

                    _model.AddMapping(map);
                    row++;
                }

                // - Salava le impostazioni avanzate
                if (!string.IsNullOrEmpty(uiTempDir.Text))
                {
                    _model.CustomLocalTempDir = uiTempDir.Text;
                }
                else
                {
                    _model.CustomLocalTempDir = null;
                }
                if (!string.IsNullOrEmpty(uiPathToArray.Text))
                {
                    _model.JsonObjectRelativePath = uiPathToArray.Text;
                }
                else
                {
                    _model.JsonObjectRelativePath = null;
                }

                _model.ParseDates = cbParseJsonDate.Checked;

                DialogResult = DialogResult.OK;

                Close();
            }
            catch (FormatException ex)
            {
                MessageBox.Show("Invalid number (max length) specified. Please fix it.");
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error has occurred: " + ex.Message);
            }
        }
Пример #13
0
        public bool ContainsField(string id, JsonTypes type)
        {
            var field = Fields[id];

            return(field != null && field.JsonType == type);
        }
Пример #14
0
 private JsonObject(string id, JsonTypes type)
 {
     Id       = id;
     JsonType = type;
     Fields   = new JsonFields(this);
 }
Пример #15
0
        public JSONDataMappingModel SaveToModel()
        {
            JSONDataMappingModel result = new JSONDataMappingModel();

            // Json root and type
            RootType root;

            Enum.TryParse <RootType>(uiRootType.SelectedValue.ToString(), out root);
            result.RootType = root;

            if (!string.IsNullOrEmpty(uiPathToArray.Text))
            {
                result.JsonRootPath = uiPathToArray.Text;
            }
            else
            {
                result.JsonRootPath = null;
            }

            // IO columns mapping
            result.ClearMapping();
            if (uiIOGrid.IsCurrentCellDirty || uiIOGrid.IsCurrentRowDirty)
            {
                uiIOGrid.CurrentRow.DataGridView.EndEdit();
                uiIOGrid.EndEdit();
                CurrencyManager cm = (CurrencyManager)uiIOGrid.BindingContext[uiIOGrid.DataSource, uiIOGrid.DataMember];
                cm.EndCurrentEdit();
            }

            // In case of error, rewrite the exception for user friendliness
            int row = 1;

            foreach (DataGridViewRow r in uiIOGrid.Rows)
            {
                if (r.IsNewRow)
                {
                    continue;
                }
                string inputName = null;
                try
                {
                    inputName = (string)r.Cells[0].Value;
                }
                catch (Exception ex)
                {
                    throw new Exception("JSON Field Name on row " + row);
                }
                int maxLen = -1;
                try
                {
                    maxLen = int.Parse((string)r.Cells[1].Value.ToString());
                }
                catch (Exception ex)
                {
                    throw new Exception("Maximum length is invalid on row " + row);
                }

                string outName = null;
                try
                {
                    outName = (string)r.Cells[2].Value;
                    if (string.IsNullOrEmpty(outName))
                    {
                        throw new ArgumentException();
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Output Column name is invalid on row " + row);
                }

                JsonTypes dataType = 0;
                try
                {
                    dataType = (JsonTypes)Enum.Parse(typeof(JsonTypes), (string)r.Cells[3].Value);
                }
                catch (Exception ex)
                {
                    throw new Exception("Column type is invalid on row " + row);
                }

                IOMapEntry map = new IOMapEntry();
                map.InputFieldPath       = inputName;
                map.OutputColName        = outName;
                map.OutputJsonColumnType = dataType;
                map.InputFieldLen        = maxLen;

                result.AddMapping(map);
                row++;
            }

            // Save the InputColumns to be copied as output
            var columnsToCopy = new List <string>();

            for (var i = 0; i < inputsCb.CheckedItems.Count; i++)
            {
                // Setup a placemark. The UI will feed this after outputcolumns are added.
                columnsToCopy.Add(inputsCb.CheckedItems[i] as string);
            }

            result.InputColumnsToCopy = columnsToCopy;

            return(result);
        }
Пример #16
0
        private void UpdateParent(object newValue, JsonTypes desiredType = JsonTypes.String)
        {
            if (desiredType != JsonTypes.Null && newValue == null)
            {
                return;
            }

            var parentObject = Parent as JObject;

            if (parentObject != null)
            {
                var prop = Value.Parent as JProperty;
                if (prop != null)
                {
                    switch (desiredType)
                    {
                    case JsonTypes.Null:
                        parentObject[prop.Name] = null;
                        break;

                    case JsonTypes.String:
                        parentObject[prop.Name] = (string)newValue;
                        break;

                    case JsonTypes.Boolean:
                        parentObject[prop.Name] = (bool)newValue;
                        break;

                    case JsonTypes.Array:
                        parentObject[prop.Name] = (JArray)newValue;
                        break;

                    case JsonTypes.Object:
                        parentObject[prop.Name] = (JObject)newValue;
                        break;
                    }
                    ObjectUpdated?.Invoke(this, new ObjectUpdatedEventArgs());
                }

                return;
            }

            var parentArray = Parent as JArray;

            if (parentArray != null)
            {
                var index = parentArray.IndexOf(Value);
                if (index != -1)
                {
                    switch (desiredType)
                    {
                    case JsonTypes.Null:
                        parentArray[index] = null;
                        break;

                    case JsonTypes.String:
                        parentArray[index] = (string)newValue;
                        break;

                    case JsonTypes.Boolean:
                        parentArray[index] = (bool)newValue;
                        break;

                    case JsonTypes.Array:
                        parentArray[index] = (JArray)newValue;
                        break;

                    case JsonTypes.Object:
                        parentArray[index] = (JObject)newValue;
                        break;
                    }
                    ObjectUpdated?.Invoke(this, new ObjectUpdatedEventArgs());
                }
                return;
            }
        }