public void WritePropertyWithNoValue()
        {
            var o = new JObject();
            o.Add(new JProperty("novalue"));

            StringAssert.Equal(@"{
  ""novalue"": null
}", o.ToString());
        }
    public void Remove()
    {
      JObject o = new JObject();
      o.Add("PropertyNameValue", new JValue(1));
      Assert.AreEqual(1, o.Children().Count());

      Assert.AreEqual(false, o.Remove("sdf"));
      Assert.AreEqual(false, o.Remove(null));
      Assert.AreEqual(true, o.Remove("PropertyNameValue"));

      Assert.AreEqual(0, o.Children().Count());
    }
    public void GenericCollectionRemove()
    {
      JValue v = new JValue(1);
      JObject o = new JObject();
      o.Add("PropertyNameValue", v);
      Assert.AreEqual(1, o.Children().Count());

      Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1))));
      Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2))));
      Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1))));
      Assert.AreEqual(true, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", v)));

      Assert.AreEqual(0, o.Children().Count());
    }
    public void TryGetValue()
    {
      JObject o = new JObject();
      o.Add("PropertyNameValue", new JValue(1));
      Assert.AreEqual(1, o.Children().Count());

      JToken t;
      Assert.AreEqual(false, o.TryGetValue("sdf", out t));
      Assert.AreEqual(null, t);

      Assert.AreEqual(false, o.TryGetValue(null, out t));
      Assert.AreEqual(null, t);

      Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t));
      Assert.AreEqual(true, JToken.DeepEquals(new JValue(1), t));
    }
        public static JContainer ToJContainer(this NameValueCollection target)
        {
            if (target != null)
            {
                var jobj = new JObject();

                foreach (var key in target.AllKeys)
                {
                    jobj.Add(new JProperty(key, target[key]));
                }

                return jobj;
            }

            return null;
        }
Example #6
0
        public JObject Transform(InstrumentationEvent instrumentationEvent)
        {
            if (instrumentationEvent == null)
            {
                return(null);
            }
            JObject logLine = BuildPayload(instrumentationEvent);

            try
            {
                logLine?.Add(DEVICE_ATTRIBUTES_KEY, BuildDeviceAttributes(instrumentationEvent));
            }
            catch (Exception ex)
            {
                throw new Exception("Exception thrown while transforming JSON", ex);
            }

            return(logLine);
        }
        public void GenericListJTokenAddBadValue()
        {
            AssertException.Throws<ArgumentException>(() =>
            {
                JProperty p1 = new JProperty("Test1", 1);
                JProperty p2 = new JProperty("Test2", "Two");
                IList<JToken> l = new JObject(p1, p2);

                // string is implicitly converted to JValue
                l.Add("Bad!");
            }, "Can not add OpenGamingLibrary.Json.Linq.JValue to OpenGamingLibrary.Json.Linq.JObject.");
        }
        /// <summary>
        /// Serialize the <see cref="IterationSetup"/>
        /// </summary>
        /// <param name="iterationSetup">The <see cref="IterationSetup"/> to serialize</param>
        /// <returns>The <see cref="JObject"/></returns>
        private JObject Serialize(IterationSetup iterationSetup)
        {
            var jsonObject = new JObject();

            jsonObject.Add("classKind", this.PropertySerializerMap["classKind"](Enum.GetName(typeof(CDP4Common.CommonData.ClassKind), iterationSetup.ClassKind)));
            jsonObject.Add("createdOn", this.PropertySerializerMap["createdOn"](iterationSetup.CreatedOn));
            jsonObject.Add("description", this.PropertySerializerMap["description"](iterationSetup.Description));
            jsonObject.Add("excludedDomain", this.PropertySerializerMap["excludedDomain"](iterationSetup.ExcludedDomain.OrderBy(x => x, this.guidComparer)));
            jsonObject.Add("excludedPerson", this.PropertySerializerMap["excludedPerson"](iterationSetup.ExcludedPerson.OrderBy(x => x, this.guidComparer)));
            jsonObject.Add("frozenOn", this.PropertySerializerMap["frozenOn"](iterationSetup.FrozenOn));
            jsonObject.Add("iid", this.PropertySerializerMap["iid"](iterationSetup.Iid));
            jsonObject.Add("isDeleted", this.PropertySerializerMap["isDeleted"](iterationSetup.IsDeleted));
            jsonObject.Add("iterationIid", this.PropertySerializerMap["iterationIid"](iterationSetup.IterationIid));
            jsonObject.Add("iterationNumber", this.PropertySerializerMap["iterationNumber"](iterationSetup.IterationNumber));
            jsonObject.Add("modifiedOn", this.PropertySerializerMap["modifiedOn"](iterationSetup.ModifiedOn));
            jsonObject.Add("revisionNumber", this.PropertySerializerMap["revisionNumber"](iterationSetup.RevisionNumber));
            jsonObject.Add("sourceIterationSetup", this.PropertySerializerMap["sourceIterationSetup"](iterationSetup.SourceIterationSetup));
            jsonObject.Add("thingPreference", this.PropertySerializerMap["thingPreference"](iterationSetup.ThingPreference));
            return(jsonObject);
        }
Example #9
0
        public static void AddLogEntry(string logEntry)
        {
            // This is just so we can manually trigger a dump to file
            if (logEntry == "SPECIALDUMP")
            {
                var logXml = LogXmlHelper.CreateLog(db);
                WriteLogFile("testLog.xml", logXml);
                return;
            }

            var lines     = logEntry.Split(Environment.NewLine);
            var logParams = lines[0].Split(',', 2);

            if (logParams.Length < 2)
            {
                throw new ArgumentException("Log params does not contain two entries");
            }

            var server      = logParams[0];
            var transaction = logParams[1];

            foreach (var line in lines.Skip(1))
            {
                if (string.IsNullOrWhiteSpace(line))
                {
                    continue;
                }

                var      type = line[0];
                string[] parts;

                var log = new Log();

                log.Server      = server;
                log.Transaction = transaction;

                try
                {
                    switch (type)
                    {
                    case 'c':     // Command
                        parts = line.Split(',', CommandParts);
                        if (parts.Length != CommandParts)
                        {
                            throw new ArgumentException($"Command entry does not have {CommandParts} parts");
                        }

                        log.LogType     = "command";
                        log.Command     = parts[1];
                        log.Username    = parts[2];
                        log.Amount      = !string.IsNullOrWhiteSpace(parts[3]) ? (decimal?)decimal.Parse(parts[3]) : null;
                        log.StockSymbol = parts[4];
                        log.Filename    = parts[5];
                        log.Timestamp   = ulong.Parse(parts[6]);

                        break;

                    case 'e':     // Event
                        parts = line.Split(',', EventParts);
                        if (parts.Length != EventParts)
                        {
                            throw new ArgumentException($"Event entry does not have {EventParts} parts");
                        }

                        log.LogType     = parts[1].ToLower();
                        log.Command     = parts[2];
                        log.Username    = parts[3];
                        log.Amount      = !string.IsNullOrWhiteSpace(parts[4]) ? (decimal?)decimal.Parse(parts[4]) : null;
                        log.StockSymbol = parts[5];
                        log.Filename    = parts[6];
                        log.Timestamp   = ulong.Parse(parts[7]);
                        log.Message     = parts[8];

                        break;

                    case 't':     // Transaction
                        parts = line.Split(',', TransactionParts);
                        if (parts.Length != TransactionParts)
                        {
                            throw new ArgumentException($"Event entry does not have {TransactionParts} parts");
                        }

                        log.LogType   = "transaction";
                        log.Username  = parts[1];
                        log.Amount    = !string.IsNullOrWhiteSpace(parts[2]) ? (decimal?)decimal.Parse(parts[2]) : null;
                        log.Timestamp = ulong.Parse(parts[3]);
                        log.Message   = parts[4];

                        break;

                    case 'q':     // Quote
                        parts = line.Split(',', QuoteParts);
                        if (parts.Length != QuoteParts)
                        {
                            throw new ArgumentException($"Event entry does not have {QuoteParts} parts");
                        }

                        log.LogType     = "quote";
                        log.Amount      = !string.IsNullOrWhiteSpace(parts[1]) ? (decimal?)decimal.Parse(parts[1]) : null;
                        log.StockSymbol = parts[2];
                        log.Username    = parts[3];
                        log.Timestamp   = ulong.Parse(parts[4]);
                        log.Cryptokey   = parts[5];

                        break;

                    case 'r':     // Request for logs to frontent
                        parts = line.Split(',', RequestParts);
                        if (parts.Length != RequestParts)
                        {
                            throw new ArgumentException($"Event entry does not have {RequestParts} parts");
                        }

                        var username  = string.IsNullOrWhiteSpace(parts[1]) ? null : parts[1];
                        var reference = parts[2];

                        // Stop the timer in case this takes a while
                        commitTimer.Stop();

                        // Commit now before creating log for user
                        Save();
                        addedLogs = 0;

                        var logXml = LogXmlHelper.CreateLog(db, username);

                        JObject response = new JObject();
                        response.Add("ref", reference);
                        response.Add("status", "ok");
                        response.Add("data", logXml);

                        RabbitHelper.PushResponse(response);

                        // Restart the loop so we don't try to log this special entry
                        continue;

                    default:
                        throw new ArgumentException($"Unknown log entry type {type}");
                    }

                    db.Logs.Add(log);

                    // Restart the commit timer
                    commitTimer.Stop();
                    commitTimer.Start();

                    if (++addedLogs > 1000)
                    {
                        Save();
                        addedLogs = 0;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Invalid entry: {line}. Exception: {e.Message}");
                    continue;
                }
            }
        }
Example #10
0
        public void IListAddBadToken()
        {
            AssertException.Throws<ArgumentException>(() =>
            {
                JProperty p1 = new JProperty("Test1", 1);
                JProperty p2 = new JProperty("Test2", "Two");
                IList l = new JObject(p1, p2);

                l.Add(new JValue("Bad!"));
            }, "Can not add OpenGamingLibrary.Json.Linq.JValue to OpenGamingLibrary.Json.Linq.JObject.");
        }
Example #11
0
        public void Iterate()
        {
            var o = new JObject();
            o.Add("PropertyNameValue1", new JValue(1));
            o.Add("PropertyNameValue2", new JValue(2));

            JToken t = o;

            int i = 1;
            foreach (JProperty property in t)
            {
                Assert.Equal("PropertyNameValue" + i, property.Name);
                Assert.Equal(i, (int)property.Value);

                i++;
            }
        }
Example #12
0
        public void GenericCollectionContains()
        {
            JValue v = new JValue(1);
            var o = new JObject();
            o.Add("PropertyNameValue", v);
            Assert.Equal(1, o.Children().Count());

            bool contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1)));
            Assert.Equal(false, contains);

            contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", v));
            Assert.Equal(true, contains);

            contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2)));
            Assert.Equal(false, contains);

            contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1)));
            Assert.Equal(false, contains);

            contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(default(KeyValuePair<string, JToken>));
            Assert.Equal(false, contains);
        }
 public void SetGlobalVariable(string propertyName, JToken value)
 {
     _injectedObjects.Add(propertyName, value.ToString(Formatting.None));
 }
Example #14
0
        private JArray GetRoles()
        {
            JArray roles = new JArray();

            CollectionRoleItemController[] controllers = rolesContainer.GetComponentsInChildren <CollectionRoleItemController>();
            foreach (CollectionRoleItemController controller in controllers)
            {
                string key             = controller.keyInput.text;
                string requiredMatches = controller.requiredMatchesDropdown.options[controller.requiredMatchesDropdown.value].text;
                string andOr           = requiredMatches == "All" ? "$and" : "$or";

                JArray criteria = new JArray();

                CollectionRoleCriteriaItemController[] criteriaControllers = controller.GetComponentsInChildren <CollectionRoleCriteriaItemController>();
                foreach (CollectionRoleCriteriaItemController criteriaController in criteriaControllers)
                {
                    JObject criterion = new JObject();

                    string field = criteriaController.fieldDropdown.options[criteriaController.fieldDropdown.value].text;
                    string operatorDropdownText = criteriaController.operatorDropdown.options[criteriaController.operatorDropdown.value].text;

                    string @operator = "";
                    switch (operatorDropdownText)
                    {
                    case "Equals":
                        @operator = "$eq";
                        break;
                    }

                    string type = criteriaController.typeDropdown.options[criteriaController.typeDropdown.value].text;
                    if (type == "Reference")
                    {
                        string reference = criteriaController.referenceDropdown.options[criteriaController.referenceDropdown.value].text;
                        criterion.Add(field, new JObject {
                            {
                                @operator, new JObject {
                                    { "$ref", reference }
                                }
                            }
                        });
                    }
                    else
                    {
                        if (criteriaController.booleanValueDropdown.gameObject.activeSelf)
                        {
                            List <TMP_Dropdown.OptionData> options = criteriaController.booleanValueDropdown.options;
                            bool value = options[criteriaController.booleanValueDropdown.value].text == "True";

                            criterion.Add(field, new JObject {
                                { @operator, value }
                            });
                        }
                        else if (criteriaController.numberValueInput.gameObject.activeSelf)
                        {
                            float value = float.Parse(criteriaController.numberValueInput.text);
                            criterion.Add(field, new JObject {
                                { @operator, value }
                            });
                        }
                        else
                        {
                            string value = criteriaController.numberValueInput.text;
                            criterion.Add(field, new JObject {
                                { @operator, value }
                            });
                        }
                    }

                    criteria.Add(criterion);
                }

                JObject jObject = new JObject {
                    { "name", key },
                    {
                        "query", new JObject {
                            { andOr, criteria }
                        }
                    }
                };

                roles.Add(jObject);
            }

            return(roles);
        }
Example #15
0
 private void AddBufferGet(JObject toAddTo, string methodName)
 {
     toAddTo.Add(JSON_PROP_BUFFER_ADD_METHOD, methodName);
 }
    public static string ObtieneReporteVencimientosPorProveedor(int pIdProveedor, string pFechaInicial, string pFechaFinal, int pIdSucursal, string pSucursal, string pFechaIni, string pFechaF)
    {
        CConexion ConexionBaseDatos = new CConexion();
        string    respuesta         = ConexionBaseDatos.ConectarBaseDatosSqlServer();
        JObject   oRespuesta        = new JObject();

        if (respuesta == "Conexion Establecida")
        {
            JObject  Modelo = new JObject();
            DateTime Fecha  = DateTime.Now;

            CSelectEspecifico ConsultaReporteProveedorDeVencimientosPorFecha = new CSelectEspecifico();
            ConsultaReporteProveedorDeVencimientosPorFecha.StoredProcedure.CommandText = "SP_Impresion_VencimientosPorFechaProveedores_Reporte";
            ConsultaReporteProveedorDeVencimientosPorFecha.StoredProcedure.Parameters.AddWithValue("@Opcion", 1);
            ConsultaReporteProveedorDeVencimientosPorFecha.StoredProcedure.Parameters.AddWithValue("@pIdProveedor", pIdProveedor);
            ConsultaReporteProveedorDeVencimientosPorFecha.StoredProcedure.Parameters.AddWithValue("@pIdUsuario", Convert.ToInt32(HttpContext.Current.Session["IdUsuario"]));
            ConsultaReporteProveedorDeVencimientosPorFecha.StoredProcedure.Parameters.AddWithValue("@pFechaInicial", pFechaInicial);
            ConsultaReporteProveedorDeVencimientosPorFecha.StoredProcedure.Parameters.AddWithValue("@pFechaFinal", pFechaFinal);
            ConsultaReporteProveedorDeVencimientosPorFecha.StoredProcedure.Parameters.AddWithValue("@pIdSucursal", pIdSucursal);
            ConsultaReporteProveedorDeVencimientosPorFecha.StoredProcedure.Parameters.AddWithValue("@pFechaInicialR", pFechaIni);
            ConsultaReporteProveedorDeVencimientosPorFecha.Llena(ConexionBaseDatos);

            if (pIdSucursal != 0)
            {
                Modelo.Add("SUCURSAL", Convert.ToString(pSucursal).ToUpper());
            }
            else
            {
                Modelo.Add("SUCURSAL", "TODAS");
            }

            if (ConsultaReporteProveedorDeVencimientosPorFecha.Registros.Read())
            {
                Modelo.Add("RAZONSOCIALRECEPTOR", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["RazonSocialReceptor"]));
                Modelo.Add("FECHA", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["Fecha"]));
                Modelo.Add("FECHAINICIAL", Convert.ToString(pFechaIni));
                Modelo.Add("FECHAFINAL", Convert.ToString(pFechaF));
                Modelo.Add("TIPOMONEDA", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["TipoMoneda"]));
                Modelo.Add("ESTADOCUENTA", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["EstadoCuenta"]));
                Modelo.Add("PROVEEDOR", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["Proveedor"]));
                Modelo.Add("NOMBRE", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["Nombre"]));
            }

            if (ConsultaReporteProveedorDeVencimientosPorFecha.Registros.NextResult())
            {
                JArray JAMovimientosFacturasVencidas = new JArray();
                while (ConsultaReporteProveedorDeVencimientosPorFecha.Registros.Read())
                {
                    JObject JMovimientoFacturasVencidas = new JObject();
                    JMovimientoFacturasVencidas.Add("FECHAFACTURA", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["FechaFactura"]));
                    JMovimientoFacturasVencidas.Add("FACTURA", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["Factura"]));
                    JMovimientoFacturasVencidas.Add("SUBTOTAL", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["Subtotal"]));
                    JMovimientoFacturasVencidas.Add("IVA", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["IVA"]));
                    JMovimientoFacturasVencidas.Add("MONTOFACTURADO", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["MontoFacturado"]));
                    JMovimientoFacturasVencidas.Add("SALDO", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["Saldo"]));
                    JMovimientoFacturasVencidas.Add("VENCE", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["Vence"]));
                    JMovimientoFacturasVencidas.Add("DIASVENCHOY", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["DiasVencidosAHoy"]));
                    JMovimientoFacturasVencidas.Add("DIASVENCIDOSFI", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["DiasVDesdeFI"]));
                    JMovimientoFacturasVencidas.Add("MONEDA", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["TipoMoneda"]));
                    JMovimientoFacturasVencidas.Add("REFERENCIA", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["Descripcion"]));
                    JAMovimientosFacturasVencidas.Add(JMovimientoFacturasVencidas);
                }
                Modelo.Add("MovimientosFacturasVencidas", JAMovimientosFacturasVencidas);
            }

            if (ConsultaReporteProveedorDeVencimientosPorFecha.Registros.NextResult())
            {
                JArray JAMovimientosFacturasCorriente = new JArray();
                while (ConsultaReporteProveedorDeVencimientosPorFecha.Registros.Read())
                {
                    JObject JMovimientoFacturasAlCorriente = new JObject();
                    JMovimientoFacturasAlCorriente.Add("FECHAFACTURA", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["FechaFactura"]));
                    JMovimientoFacturasAlCorriente.Add("FACTURA", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["Factura"]));
                    JMovimientoFacturasAlCorriente.Add("SUBTOTAL", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["Subtotal"]));
                    JMovimientoFacturasAlCorriente.Add("IVA", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["IVA"]));
                    JMovimientoFacturasAlCorriente.Add("MONTOFACTURADO", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["MontoFacturado"]));
                    JMovimientoFacturasAlCorriente.Add("SALDO", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["Saldo"]));
                    JMovimientoFacturasAlCorriente.Add("VENCE", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["Vence"]));
                    JMovimientoFacturasAlCorriente.Add("DIASPORVENCER", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["DiasFaltanVencer"]));
                    JMovimientoFacturasAlCorriente.Add("MONEDA", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["TipoMoneda"]));
                    JMovimientoFacturasAlCorriente.Add("REFERENCIA", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["Descripcion"]));
                    JAMovimientosFacturasCorriente.Add(JMovimientoFacturasAlCorriente);
                }
                Modelo.Add("MovimientosFacturasAlCorriente", JAMovimientosFacturasCorriente);
            }


            if (ConsultaReporteProveedorDeVencimientosPorFecha.Registros.NextResult())
            {
                JArray JAMovimientosFacturasVencidasDolares = new JArray();
                while (ConsultaReporteProveedorDeVencimientosPorFecha.Registros.Read())
                {
                    JObject JMovimientoFacturasVencidasDolares = new JObject();
                    JMovimientoFacturasVencidasDolares.Add("FECHAFACTURA", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["FechaFactura"]));
                    JMovimientoFacturasVencidasDolares.Add("FACTURA", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["Factura"]));
                    JMovimientoFacturasVencidasDolares.Add("SUBTOTAL", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["Subtotal"]));
                    JMovimientoFacturasVencidasDolares.Add("IVA", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["IVA"]));
                    JMovimientoFacturasVencidasDolares.Add("MONTOFACTURADO", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["MontoFacturado"]));
                    JMovimientoFacturasVencidasDolares.Add("SALDO", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["Saldo"]));
                    JMovimientoFacturasVencidasDolares.Add("VENCE", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["Vence"]));
                    JMovimientoFacturasVencidasDolares.Add("DIASVENCHOY", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["DiasVencidosAHoy"]));
                    JMovimientoFacturasVencidasDolares.Add("DIASVENCIDOSFI", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["DiasVDesdeFI"]));
                    JMovimientoFacturasVencidasDolares.Add("MONEDA", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["TipoMoneda"]));
                    JMovimientoFacturasVencidasDolares.Add("REFERENCIA", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["Descripcion"]));
                    JAMovimientosFacturasVencidasDolares.Add(JMovimientoFacturasVencidasDolares);
                }
                Modelo.Add("MovimientosFacturasVencidasDolares", JAMovimientosFacturasVencidasDolares);
            }

            if (ConsultaReporteProveedorDeVencimientosPorFecha.Registros.NextResult())
            {
                JArray JAMovimientosFacturasCorrienteDolares = new JArray();
                while (ConsultaReporteProveedorDeVencimientosPorFecha.Registros.Read())
                {
                    JObject JMovimientoFacturasAlCorrienteDolares = new JObject();
                    JMovimientoFacturasAlCorrienteDolares.Add("FECHAFACTURA", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["FechaFactura"]));
                    JMovimientoFacturasAlCorrienteDolares.Add("FACTURA", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["Factura"]));
                    JMovimientoFacturasAlCorrienteDolares.Add("SUBTOTAL", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["Subtotal"]));
                    JMovimientoFacturasAlCorrienteDolares.Add("IVA", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["IVA"]));
                    JMovimientoFacturasAlCorrienteDolares.Add("MONTOFACTURADO", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["MontoFacturado"]));
                    JMovimientoFacturasAlCorrienteDolares.Add("SALDO", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["Saldo"]));
                    JMovimientoFacturasAlCorrienteDolares.Add("VENCE", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["Vence"]));
                    JMovimientoFacturasAlCorrienteDolares.Add("DIASPORVENCER", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["DiasFaltanVencer"]));
                    JMovimientoFacturasAlCorrienteDolares.Add("MONEDA", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["TipoMoneda"]));
                    JMovimientoFacturasAlCorrienteDolares.Add("REFERENCIA", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["Descripcion"]));
                    JAMovimientosFacturasCorrienteDolares.Add(JMovimientoFacturasAlCorrienteDolares);
                }
                Modelo.Add("MovimientosFacturasAlCorrienteDolares", JAMovimientosFacturasCorrienteDolares);
            }

            if (ConsultaReporteProveedorDeVencimientosPorFecha.Registros.NextResult())
            {
                if (ConsultaReporteProveedorDeVencimientosPorFecha.Registros.Read())
                {
                    Modelo.Add("VENCIDASENPESOS", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["SaldoFacturasVencidasPesos"]));
                    Modelo.Add("PORVENCERENPESOS", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["SaldoFacturasAlCorrientePesos"]));
                    Modelo.Add("VENCIDASENDOLARES", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["SaldoFacturasVencidasDolares"]));
                    Modelo.Add("PORVENCERENDOLARES", Convert.ToString(ConsultaReporteProveedorDeVencimientosPorFecha.Registros["SaldoFacturasAlCorrienteDolares"]));
                }
            }

            oRespuesta.Add(new JProperty("Error", 0));
            oRespuesta.Add(new JProperty("Modelo", Modelo));
        }
        else
        {
            oRespuesta.Add(new JProperty("Error", 1));
            oRespuesta.Add(new JProperty("Descripcion", "No hay conexion a base de datos"));
        }


        ConexionBaseDatos.CerrarBaseDatosSqlServer();
        return(oRespuesta.ToString());
    }
        private async Task <bool> InvokeCryptographyEndpointAsync()
        {
            // Metadata requests must be made via GET.
            // See http://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationRequest
            if (!string.Equals(Request.Method, "GET", StringComparison.OrdinalIgnoreCase))
            {
                Logger.LogError("The discovery request was rejected because an invalid " +
                                "HTTP method was used: {Method}.", Request.Method);

                return(await SendCryptographyResponseAsync(new OpenIdConnectResponse
                {
                    Error = OpenIdConnectConstants.Errors.InvalidRequest,
                    ErrorDescription = "Invalid HTTP method: make sure to use GET."
                }));
            }

            var request = new OpenIdConnectRequest(Request.Query);

            // Note: set the message type before invoking the ExtractCryptographyRequest event.
            request.SetProperty(OpenIdConnectConstants.Properties.MessageType,
                                OpenIdConnectConstants.MessageTypes.CryptographyRequest);

            // Store the discovery request in the OWIN context.
            Context.SetOpenIdConnectRequest(request);

            var @event = new ExtractCryptographyRequestContext(Context, Options, request);
            await Options.Provider.ExtractCryptographyRequest(@event);

            if (@event.HandledResponse)
            {
                Logger.LogDebug("The discovery request was handled in user code.");

                return(true);
            }

            else if (@event.Skipped)
            {
                Logger.LogDebug("The default discovery request handling was skipped from user code.");

                return(false);
            }

            else if (@event.IsRejected)
            {
                Logger.LogError("The discovery request was rejected with the following error: {Error} ; {Description}",
                                /* Error: */ @event.Error ?? OpenIdConnectConstants.Errors.InvalidRequest,
                                /* Description: */ @event.ErrorDescription);

                return(await SendCryptographyResponseAsync(new OpenIdConnectResponse
                {
                    Error = @event.Error ?? OpenIdConnectConstants.Errors.InvalidRequest,
                    ErrorDescription = @event.ErrorDescription,
                    ErrorUri = @event.ErrorUri
                }));
            }

            Logger.LogInformation("The discovery request was successfully extracted " +
                                  "from the HTTP request: {Request}", request);

            var context = new ValidateCryptographyRequestContext(Context, Options, request);
            await Options.Provider.ValidateCryptographyRequest(context);

            if (context.HandledResponse)
            {
                Logger.LogDebug("The discovery request was handled in user code.");

                return(true);
            }

            else if (context.Skipped)
            {
                Logger.LogDebug("The default discovery request handling was skipped from user code.");

                return(false);
            }

            else if (!context.IsValidated)
            {
                Logger.LogError("The discovery request was rejected with the following error: {Error} ; {Description}",
                                /* Error: */ context.Error ?? OpenIdConnectConstants.Errors.InvalidRequest,
                                /* Description: */ context.ErrorDescription);

                return(await SendCryptographyResponseAsync(new OpenIdConnectResponse
                {
                    Error = context.Error ?? OpenIdConnectConstants.Errors.InvalidRequest,
                    ErrorDescription = context.ErrorDescription,
                    ErrorUri = context.ErrorUri
                }));
            }

            var notification = new HandleCryptographyRequestContext(Context, Options, request);

            foreach (var credentials in Options.SigningCredentials)
            {
                // If the signing key is not an asymmetric key, ignore it.
                if (!(credentials.SigningKey is AsymmetricSecurityKey))
                {
                    continue;
                }

                if (!credentials.SigningKey.IsSupportedAlgorithm(SecurityAlgorithms.RsaSha256Signature))
                {
                    Logger.LogInformation("An unsupported signing key was ignored and excluded from the " +
                                          "key set: {Type}. Only RSA asymmetric security keys can be exposed " +
                                          "via the JWKS endpoint.", credentials.SigningKey.GetType().Name);

                    continue;
                }

                // Try to extract a key identifier from the credentials.
                LocalIdKeyIdentifierClause identifier = null;
                credentials.SigningKeyIdentifier?.TryFind(out identifier);

                // Resolve the underlying algorithm from the security key.
                var algorithm = ((AsymmetricSecurityKey)credentials.SigningKey)
                                .GetAsymmetricAlgorithm(
                    algorithm: SecurityAlgorithms.RsaSha256Signature,
                    privateKey: false) as RSA;

                // Skip the key if an algorithm instance cannot be extracted.
                if (algorithm == null)
                {
                    Logger.LogWarning("A signing key was ignored because it was unable " +
                                      "to provide the requested algorithm instance.");

                    continue;
                }

                // Export the RSA public key to create a new JSON Web Key
                // exposing the exponent and the modulus parameters.
                var parameters = algorithm.ExportParameters(includePrivateParameters: false);

                Debug.Assert(parameters.Exponent != null &&
                             parameters.Modulus != null,
                             "RSA.ExportParameters() shouldn't return null parameters.");

                var key = new JsonWebKey
                {
                    Use = JsonWebKeyUseNames.Sig,
                    Kty = JsonWebAlgorithmsKeyTypes.RSA,

                    // Resolve the JWA identifier from the algorithm specified in the credentials.
                    Alg = OpenIdConnectServerHelpers.GetJwtAlgorithm(credentials.SignatureAlgorithm),

                    // Use the key identifier specified
                    // in the signing credentials.
                    Kid = identifier?.LocalId,

                    // Note: both E and N must be base64url-encoded.
                    // See https://tools.ietf.org/html/rfc7518#section-6.2.1.2
                    E = Base64UrlEncoder.Encode(parameters.Exponent),
                    N = Base64UrlEncoder.Encode(parameters.Modulus)
                };

                X509Certificate2 certificate = null;

                // Determine whether the signing credentials are directly based on a X.509 certificate.
                var x509SigningCredentials = credentials as X509SigningCredentials;
                if (x509SigningCredentials != null)
                {
                    certificate = x509SigningCredentials.Certificate;
                }

                // Skip looking for a X509SecurityKey in SigningCredentials.SigningKey
                // if a certificate has been found in the SigningCredentials instance.
                if (certificate == null)
                {
                    // Determine whether the security key is an asymmetric key embedded in a X.509 certificate.
                    var x509SecurityKey = credentials.SigningKey as X509SecurityKey;
                    if (x509SecurityKey != null)
                    {
                        certificate = x509SecurityKey.Certificate;
                    }
                }

                // Skip looking for a X509AsymmetricSecurityKey in SigningCredentials.SigningKey
                // if a certificate has been found in SigningCredentials or SigningCredentials.SigningKey.
                if (certificate == null)
                {
                    // Determine whether the security key is an asymmetric key embedded in a X.509 certificate.
                    var x509AsymmetricSecurityKey = credentials.SigningKey as X509AsymmetricSecurityKey;
                    if (x509AsymmetricSecurityKey != null)
                    {
                        // The X.509 certificate is not directly accessible when using X509AsymmetricSecurityKey.
                        // Reflection is the only way to get the certificate used to create the security key.
                        var field = typeof(X509AsymmetricSecurityKey).GetField(
                            name: "certificate",
                            bindingAttr: BindingFlags.Instance | BindingFlags.NonPublic);
                        Debug.Assert(field != null);

                        certificate = (X509Certificate2)field.GetValue(x509AsymmetricSecurityKey);
                    }
                }

                // If the signing key is embedded in a X.509 certificate, set
                // the x5t and x5c parameters using the certificate details.
                if (certificate != null)
                {
                    // x5t must be base64url-encoded.
                    // See https://tools.ietf.org/html/rfc7517#section-4.8
                    key.X5t = Base64UrlEncoder.Encode(certificate.GetCertHash());

                    // Unlike E or N, the certificates contained in x5c
                    // must be base64-encoded and not base64url-encoded.
                    // See https://tools.ietf.org/html/rfc7517#section-4.7
                    key.X5c.Add(Convert.ToBase64String(certificate.RawData));
                }

                notification.Keys.Add(key);
            }

            await Options.Provider.HandleCryptographyRequest(notification);

            if (notification.HandledResponse)
            {
                Logger.LogDebug("The discovery request was handled in user code.");

                return(true);
            }

            else if (notification.Skipped)
            {
                Logger.LogDebug("The default discovery request handling was skipped from user code.");

                return(false);
            }

            else if (notification.IsRejected)
            {
                Logger.LogError("The discovery request was rejected with the following error: {Error} ; {Description}",
                                /* Error: */ notification.Error ?? OpenIdConnectConstants.Errors.InvalidRequest,
                                /* Description: */ notification.ErrorDescription);

                return(await SendCryptographyResponseAsync(new OpenIdConnectResponse
                {
                    Error = notification.Error ?? OpenIdConnectConstants.Errors.InvalidRequest,
                    ErrorDescription = notification.ErrorDescription,
                    ErrorUri = notification.ErrorUri
                }));
            }

            var keys = new JArray();

            foreach (var key in notification.Keys)
            {
                var item = new JObject();

                // Ensure a key type has been provided.
                // See https://tools.ietf.org/html/rfc7517#section-4.1
                if (string.IsNullOrEmpty(key.Kty))
                {
                    Logger.LogError("A JSON Web Key was excluded from the key set because " +
                                    "it didn't contain the mandatory 'kid' parameter.");

                    continue;
                }

                // Create a dictionary associating the
                // JsonWebKey components with their values.
                var parameters = new Dictionary <string, string>
                {
                    [JsonWebKeyParameterNames.Kid]    = key.Kid,
                    [JsonWebKeyParameterNames.Use]    = key.Use,
                    [JsonWebKeyParameterNames.Kty]    = key.Kty,
                    [JsonWebKeyParameterNames.KeyOps] = key.KeyOps,
                    [JsonWebKeyParameterNames.Alg]    = key.Alg,
                    [JsonWebKeyParameterNames.E]      = key.E,
                    [JsonWebKeyParameterNames.N]      = key.N,
                    [JsonWebKeyParameterNames.X5t]    = key.X5t,
                    [JsonWebKeyParameterNames.X5u]    = key.X5u
                };

                foreach (var parameter in parameters)
                {
                    if (!string.IsNullOrEmpty(parameter.Value))
                    {
                        item.Add(parameter.Key, parameter.Value);
                    }
                }

                if (key.X5c.Count != 0)
                {
                    item.Add(JsonWebKeyParameterNames.X5c, new JArray(key.X5c));
                }

                keys.Add(item);
            }

            return(await SendCryptographyResponseAsync(new OpenIdConnectResponse
            {
                [OpenIdConnectConstants.Parameters.Keys] = keys
            }));
        }
Example #18
0
        public JObject ParseProperties(string modelName, CompositeValueProvider valueProvider, JObject model)
        {
            IDictionary <string, string> properties = valueProvider.GetKeysFromPrefix(modelName);

            _logger.LogDebug("DynamicModelBinder property count is " + properties.Count() + " for " + modelName);

            List <string> subModelNames = new List <string>();
            List <string> arrModelNames = new List <string>();

            foreach (var property in properties)
            {
                var subProperties = valueProvider.GetKeysFromPrefix(property.Value);

                var key      = property.Value;
                var propName = property.Key;

                if (subProperties.Count == 0)
                {
                    if (!propName.Contains("RequestVerification"))
                    {
                        if (!model.ContainsKey(propName))
                        {
                            model.Add(propName, GetValue(valueProvider, key));
                        }
                        else
                        {
                            model[propName] = GetValue(valueProvider, key);
                        }
                    }
                }
                else if (subProperties.Any(sp => sp.Value.Contains("[")))
                {
                    if (!arrModelNames.Contains(propName))
                    {
                        arrModelNames.Add(propName);
                    }
                }
                else
                {
                    if (!subModelNames.Contains(propName))
                    {
                        subModelNames.Add(propName);
                    }
                }
            }

            foreach (var subModelName in subModelNames)
            {
                var key = properties[subModelName];

                JObject val = ParseProperties(key, valueProvider, model.ContainsKey(subModelName) ? (JObject)model[subModelName] : new JObject());
                if (!model.ContainsKey(subModelName))
                {
                    model.Add(subModelName, val);
                }
                else
                {
                    model[subModelName] = val;
                }
            }

            foreach (var arrModelName in arrModelNames)
            {
                var key            = properties[arrModelName];
                var arrKeys        = valueProvider.GetKeysFromPrefix(key);
                var isComplexArray = false;
                foreach (var arrKey in arrKeys)
                {
                    var subProperties = valueProvider.GetKeysFromPrefix(arrKey.Value);
                    if (subProperties.Count > 0)
                    {
                        isComplexArray = true;
                    }
                }

                JToken arrResult = null;

                List <object> vals = new List <object>();

                vals.Cast <Object>().ToList();
                if (isComplexArray)
                {
                    foreach (var arrKey in arrKeys)
                    {
                        var arrItemKey = arrKey.Value;

                        var subProperties = valueProvider.GetKeysFromPrefix(arrItemKey);
                        if (subProperties.Count > 0)
                        {
                            object val = ParseProperties(arrItemKey, valueProvider, new JObject());
                            vals.Add(val);
                        }
                    }

                    arrResult = new JArray(vals);
                }
                else
                {
                    foreach (var arrKey in arrKeys)
                    {
                        var arrItemKey = arrKey.Value;
                        vals.Add(GetValue(valueProvider, arrItemKey));
                    }

                    arrResult = new JArray(vals);

                    bool castToType = true;
                    Type itemType   = vals[0].GetType();
                    foreach (var item in vals)
                    {
                        if (item.GetType() != itemType)
                        {
                            castToType = false;
                            break;
                        }
                    }

                    if (castToType)
                    {
                        var ienumerable = typeof(Enumerable).GetMethod("Cast").MakeGenericMethod(itemType).Invoke(null, new object[] { vals });
                        arrResult = new JArray(typeof(Enumerable).GetMethod("ToList").MakeGenericMethod(itemType).Invoke(null, new object[] { ienumerable }));
                    }
                }

                if (!model.ContainsKey(arrModelName))
                {
                    model.Add(arrModelName, arrResult);
                }
                else
                {
                    model[arrModelName] = arrResult;
                }
            }

            return(model);
        }
Example #19
0
        public async Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            var modelName = bindingContext.ModelName;

            var valueProvider = await CompositeValueProvider.CreateAsync(bindingContext.ActionContext, new CopyOnWriteList <IValueProviderFactory>(_valueProviderFactories));

            JObject model = bindingContext.Model != null ? (JObject)bindingContext.Model : new JObject();

            //Form/Route/Query
            if (bindingContext.ModelMetadata.BindingSource == null || bindingContext.ModelMetadata.BindingSource.CanAcceptDataFrom(BindingSource.Form) || bindingContext.ModelMetadata.BindingSource.CanAcceptDataFrom(BindingSource.Query) || bindingContext.ModelMetadata.BindingSource.CanAcceptDataFrom(BindingSource.Path))
            {
                model = ParseProperties(modelName, valueProvider, model);
            }

            //Route
            if (bindingContext.IsTopLevelObject)
            {
                if (bindingContext.ModelMetadata.BindingSource == null || bindingContext.ModelMetadata.BindingSource.CanAcceptDataFrom(BindingSource.Path))
                {
                    foreach (var kvp in bindingContext.ActionContext.RouteData.Values)
                    {
                        if (kvp.Key != "area" && kvp.Key != "controller" && kvp.Key != "action" && !model.ContainsKey(kvp.Key))
                        {
                            var stringValue = kvp.Value as string ?? Convert.ToString(kvp.Value, CultureInfo.InvariantCulture) ?? string.Empty;
                            if (!model.ContainsKey(kvp.Key))
                            {
                                model.Add(kvp.Key, GetValue(stringValue));
                            }
                            else if (bindingContext.HttpContext.Request.Query.ContainsKey(kvp.Key) && !bindingContext.HttpContext.Request.Form.ContainsKey(kvp.Key))
                            {
                                model[kvp.Key] = GetValue(stringValue);
                            }
                        }
                    }
                }
            }

            //Query
            if (bindingContext.IsTopLevelObject)
            {
                if (bindingContext.ModelMetadata.BindingSource == null || bindingContext.ModelMetadata.BindingSource.CanAcceptDataFrom(BindingSource.Query))
                {
                    foreach (var kvp in bindingContext.HttpContext.Request.Query)
                    {
                        if (!model.ContainsKey(kvp.Key))
                        {
                            model.Add(kvp.Key, GetValue(kvp.Value));
                        }
                        else if (!bindingContext.HttpContext.Request.Form.ContainsKey(kvp.Key) && !bindingContext.ActionContext.RouteData.Values.ContainsKey(kvp.Key))
                        {
                            model[kvp.Key] = GetValue(kvp.Value);
                        }
                    }
                }
            }

            bindingContext.Result = ModelBindingResult.Success(model);
        }
Example #20
0
 public void DuplicatePropertyNameShouldThrow()
 {
     AssertException.Throws<ArgumentException>(() =>
     {
         var o = new JObject();
         o.Add("PropertyNameValue", null);
         o.Add("PropertyNameValue", null);
     }, "Can not add property PropertyNameValue to OpenGamingLibrary.Json.Linq.JObject. Property with the same name already exists on object.");
 }
Example #21
0
        public void EmptyObjectDeepEquals()
        {
            Assert.True(JToken.DeepEquals(new JObject(), new JObject()));

            JObject a = new JObject();
            JObject b = new JObject();

            b.Add("hi", "bye");
            b.Remove("hi");

            Assert.True(JToken.DeepEquals(a, b));
            Assert.True(JToken.DeepEquals(b, a));
        }
Example #22
0
 private static void AddHost(JObject swagger, string swaggerHost)
 {
     swagger.Add(SwaggerProperties.Host, swaggerHost);
 }
Example #23
0
        public void GenericCollectionCopyTo()
        {
            var o = new JObject();
            o.Add("PropertyNameValue", new JValue(1));
            o.Add("PropertyNameValue2", new JValue(2));
            o.Add("PropertyNameValue3", new JValue(3));
            Assert.Equal(3, o.Children().Count());

            KeyValuePair<string, JToken>[] a = new KeyValuePair<string, JToken>[5];

            ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(a, 1);

            Assert.Equal(default(KeyValuePair<string, JToken>), a[0]);

            Assert.Equal("PropertyNameValue", a[1].Key);
            Assert.Equal(1, (int)a[1].Value);

            Assert.Equal("PropertyNameValue2", a[2].Key);
            Assert.Equal(2, (int)a[2].Value);

            Assert.Equal("PropertyNameValue3", a[3].Key);
            Assert.Equal(3, (int)a[3].Value);

            Assert.Equal(default(KeyValuePair<string, JToken>), a[4]);
        }
 //数据库操作成功
 private void OperatorSuccess(List <PVPGameRoom> pvpGameRooms, JObject responseData)
 {
     responseData.Add(MyCommon.CODE, (int)Consts.Code.Code_OK);
     responseData.Add("room_list", JsonConvert.SerializeObject(pvpGameRooms));
 }
Example #25
0
        private static void OnMessage(string message)
        {
            message = HasData(message);

            if (message == null)
            {
                _socket.Send("42[\"manual\",{}]");
                return;
            }

            Message msg = JsonConvert.DeserializeObject <Message>(message);

            double brake_speed  = 0;
            bool   car_in_front = false;

            for (int i = 0; i < msg.sensor_fusion.Length; i++)
            {
                double[] car_data = msg.sensor_fusion[i];
                double   vx       = car_data[3];
                double   vy       = car_data[4];
                double   s        = car_data[5];
                double   d        = car_data[6];

                if (d > lane * LANE_WIDTH && d < (lane + 1) * LANE_WIDTH)
                {
                    double distance           = s - msg.s;
                    double distance_threshold = msg.speed / 1.2;

                    if (s > msg.s && distance < distance_threshold)
                    {
                        double distance_violation = distance_threshold - distance;
                        double car_vel_mph        = Math.Sqrt(vx * vx + vy * vy) * MS_TO_MPH;
                        double speed_diff         = desired_velocity_mph - car_vel_mph;
                        brake_speed  = speed_diff * BRAKE_SPEED_FACTOR + distance_violation * BRAKE_DIST_FACTOR;
                        car_in_front = true;

                        break;
                    }
                }
            }

            if (car_in_front)
            {
                brake_speed           = brake_speed > MAX_SPEED_DIFF ? MAX_SPEED_DIFF : brake_speed;
                desired_velocity_mph -= brake_speed;
            }
            // Don't use msg.speed, it lags behind and will cause desired velocity to get too high
            else if (desired_velocity_mph < TARGET_VELOCITY_MPH)
            {
                desired_velocity_mph += MAX_SPEED_DIFF;
            }

            if (current_action == null)
            {
                LaneChangeInfo info_left  = CheckCarsOnAdjacentLane(-1, msg.s, msg.sensor_fusion);
                LaneChangeInfo info_right = CheckCarsOnAdjacentLane(1, msg.s, msg.sensor_fusion);

                List <PathPlannerAction> actions = new List <PathPlannerAction>();
                double straight_cost             = Math.Abs(TARGET_VELOCITY_MPH - desired_velocity_mph) * SPEED_COST + Math.Abs(lane - DESIRED_LANE) * LANE_COST;
                actions.Add(new PathPlannerAction(0, straight_cost));

                // TODO: Use timer
                int time_since_last_last_change = Environment.TickCount - last_lane_change;

                if (time_since_last_last_change > TIME_UNTIL_NEXT_LANE_CHANGE_MS && (lane != DESIRED_LANE || car_in_front))
                {
                    if (info_left != null)
                    {
                        double lane_change_left_cost = Math.Abs((lane - 1) - DESIRED_LANE) * LANE_COST + info_left.AdjacentCarDeltaSpeed * SPEED_COST;
                        actions.Add(new PathPlannerAction(-1, lane_change_left_cost));
                    }
                    if (info_right != null)
                    {
                        double lane_change_right_cost = Math.Abs((lane + 1) - DESIRED_LANE) * LANE_COST + info_right.AdjacentCarDeltaSpeed * SPEED_COST;
                        actions.Add(new PathPlannerAction(1, lane_change_right_cost));
                    }
                }

                // Round the costs to filter out jitters. If values are the same, straight will be preferred
                // as this action is the first one in the list
                PathPlannerAction desired_action = actions.OrderBy(a => Math.Round(a.Cost)).First();
                lane += desired_action.LaneShift;
                if (desired_action.LaneShift != 0)
                {
                    current_action = desired_action;
                }
            }
            else
            {
                if (msg.d > lane * LANE_WIDTH && msg.d < (lane + 1) * LANE_WIDTH)
                {
                    current_action   = null;
                    last_lane_change = Environment.TickCount;
                }
            }

            double desired_velocity_ms = desired_velocity_mph * MPH_TO_MS;

            double smooth_step = desired_velocity_ms * TIME_TO_REACH_POINT;

            double[] rough_x   = new double[NUMBER_OF_ROUGH_POINTS];
            double[] rough_y   = new double[NUMBER_OF_ROUGH_POINTS];
            int      prev_size = msg.previous_path_x.Length;

            double ref_x   = msg.x;
            double ref_y   = msg.y;
            double ref_yaw = deg2rad(msg.yaw);

            if (prev_size < 2)
            {
                double prev_car_x = msg.x - Math.Cos(msg.yaw);
                double prev_car_y = msg.y - Math.Sin(msg.yaw);
                rough_x[0] = prev_car_x;
                rough_x[1] = msg.x;
                rough_y[0] = prev_car_y;
                rough_y[1] = msg.y;
            }
            else
            {
                ref_x = msg.previous_path_x[prev_size - 1];
                ref_y = msg.previous_path_y[prev_size - 1];
                double ref_x_prev = msg.previous_path_x[prev_size - 2];
                double ref_y_prev = msg.previous_path_y[prev_size - 2];
                ref_yaw = Math.Atan2(ref_y - ref_y_prev, ref_x - ref_x_prev);

                rough_x[0] = ref_x_prev;
                rough_x[1] = ref_x;
                rough_y[0] = ref_y_prev;
                rough_y[1] = ref_y;
            }

            for (int i = 2; i < NUMBER_OF_ROUGH_POINTS; i++)
            {
                double   next_s = msg.s + (i - 1) * ROUGH_STEP_SIZE * (current_action == null ? 1.0 : LANE_CHANGE_ROUGH_STEP_SIZE_FACTOR);
                double   next_d = GetCenterOfLane(lane);
                double[] xy     = getXY(next_s, next_d);
                rough_x[i] = xy[0];
                rough_y[i] = xy[1];
            }

            double yaw_sin = Math.Sin(-ref_yaw);
            double yaw_cos = Math.Cos(-ref_yaw);

            for (int i = 0; i < NUMBER_OF_ROUGH_POINTS; i++)
            {
                double shift_x = rough_x[i] - ref_x;
                double shift_y = rough_y[i] - ref_y;
                rough_x[i] = shift_x * yaw_cos - shift_y * yaw_sin;
                rough_y[i] = shift_x * yaw_sin + shift_y * yaw_cos;
            }

            CubicSpline spline = new CubicSpline(rough_x, rough_y);

            double[] next_x_vals = new double[NUMBER_OF_PATH_POINTS];
            double[] next_y_vals = new double[NUMBER_OF_PATH_POINTS];

            for (int i = 0; i < prev_size; i++)
            {
                next_x_vals[i] = msg.previous_path_x[i];
                next_y_vals[i] = msg.previous_path_y[i];
            }

            yaw_sin = Math.Sin(ref_yaw);
            yaw_cos = Math.Cos(ref_yaw);

            for (int i = 0; i < next_x_vals.Length - prev_size; i++)
            {
                double x_point = (i + 1) * smooth_step;
                double y_point = spline.Eval(new double[] { x_point })[0];

                double x_ref = x_point;

                x_point  = x_ref * yaw_cos - y_point * yaw_sin;
                y_point  = x_ref * yaw_sin + y_point * yaw_cos;
                x_point += ref_x;
                y_point += ref_y;

                next_x_vals[prev_size + i] = x_point;
                next_y_vals[prev_size + i] = y_point;
            }

            JObject answer = new JObject();

            answer.Add("next_x", JToken.FromObject(next_x_vals));
            answer.Add("next_y", JToken.FromObject(next_y_vals));
            string answer_str = "42[\"control\"," + answer.ToString() + "]";

            _socket.Send(answer_str);
        }
 //数据库操作失败
 private void OperatorFail(JObject responseData)
 {
     responseData.Add(MyCommon.CODE, (int)Consts.Code.Code_CommonFail);
 }
Example #27
0
        public void IListAddPropertyWithExistingName()
        {
            AssertException.Throws<ArgumentException>(() =>
            {
                JProperty p1 = new JProperty("Test1", 1);
                JProperty p2 = new JProperty("Test2", "Two");
                IList l = new JObject(p1, p2);

                JProperty p3 = new JProperty("Test2", "II");

                l.Add(p3);
            }, "Can not add property Test2 to OpenGamingLibrary.Json.Linq.JObject. Property with the same name already exists on object.");
        }
Example #28
0
        private void Connect()
        {
            try
            {
                connection.On <string, string>("returnPS", (s1, s2) =>
                {
                    TimeSpan timeout   = new TimeSpan(0, 5, 0); //default timeout = 5min
                    DateTime dStart    = DateTime.Now;
                    TimeSpan dDuration = DateTime.Now - dStart;

                    using (PowerShell PowerShellInstance = PowerShell.Create())
                    {
                        Trace.WriteLine(DateTime.Now.ToString() + "\t run PS... " + s1);
                        try
                        {
                            PowerShellInstance.AddScript(s1);
                            PSDataCollection <PSObject> outputCollection = new PSDataCollection <PSObject>();

                            outputCollection.DataAdding += ConsoleOutput;
                            PowerShellInstance.Streams.Error.DataAdding += ConsoleError;

                            IAsyncResult async = PowerShellInstance.BeginInvoke <PSObject, PSObject>(null, outputCollection);
                            while (async.IsCompleted == false || dDuration > timeout)
                            {
                                Thread.Sleep(200);
                                dDuration = DateTime.Now - dStart;
                                if (tReInit.Interval > 5000)
                                {
                                    tReInit.Interval = 5000;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("There was an error: {0}", ex.Message);
                        }
                    }

                    Program.MinimizeFootprint();
                });

                //New 0.9.0.6
                connection.On <string, string>("returnPSAsync", (s1, s2) =>
                {
                    Trace.WriteLine(DateTime.Now.ToString() + "\t run PS async... " + s1);
                    var tSWScan = Task.Run(() =>
                    {
                        using (PowerShell PowerShellInstance = PowerShell.Create())
                        {
                            try
                            {
                                PowerShellInstance.AddScript(s1);
                                var PSResult = PowerShellInstance.Invoke();
                                if (PSResult.Count() > 0)
                                {
                                    string sResult = PSResult.Last().BaseObject.ToString();

                                    if (!string.IsNullOrEmpty(sResult)) //Do not return empty results
                                    {
                                        if (sResult != sScriptResult)
                                        {
                                            sScriptResult    = sResult;
                                            Random rnd       = new Random();
                                            tReInit.Interval = rnd.Next(200, Properties.Settings.Default.StatusDelay); //wait max Xs to ReInit
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("There was an error: {0}", ex.Message);
                            }
                        }

                        Program.MinimizeFootprint();
                    });
                });

                connection.On <string>("init", (s1) =>
                {
                    try
                    {
                        Trace.Write(DateTime.Now.ToString() + "\t Agent init... ");
                        connection.SendAsync("Init", Hostname).ContinueWith(task1 =>
                        {
                        });
                        Trace.WriteLine(" done.");
                    }
                    catch { }
                    try
                    {
                        foreach (string sGroup in Properties.Settings.Default.Groups.Split(';'))
                        {
                            connection.SendAsync("JoinGroup", sGroup).ContinueWith(task1 =>
                            {
                            });
                        }
                        Program.MinimizeFootprint();
                    }
                    catch { }
                });

                connection.On <string>("reinit", (s1) =>
                {
                    try
                    {
                        //Properties.Settings.Default.InventorySuccess = new DateTime();
                        //Properties.Settings.Default.HealthCheckSuccess = new DateTime();
                        //Properties.Settings.Default.Save();

                        Random rnd       = new Random();
                        tReInit.Interval = rnd.Next(200, Properties.Settings.Default.StatusDelay); //wait max 5s to ReInit
                    }
                    catch { }
                });

                connection.On <string>("status", (s1) =>
                {
                    try
                    {
                        Trace.Write(DateTime.Now.ToString() + "\t send status...");
                        string sResult = "{}";
                        using (PowerShell PowerShellInstance = PowerShell.Create())
                        {
                            try
                            {
                                PowerShellInstance.AddScript(Properties.Settings.Default.PSStatus);
                                var PSResult = PowerShellInstance.Invoke();
                                if (PSResult.Count() > 0)
                                {
                                    sResult      = PSResult.Last().BaseObject.ToString();
                                    sResult      = sResult.Replace(Environment.MachineName, Hostname);
                                    JObject jRes = JObject.Parse(sResult);
                                    jRes.Add("ScriptResult", sScriptResult);
                                    jRes.Add("Groups", Properties.Settings.Default.Groups);
                                    sResult = jRes.ToString();
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(" There was an error: {0}", ex.Message);
                            }
                        }

                        //connection.InvokeAsync("Status", new object[] { Hostname, sResult }).ContinueWith(task1 =>
                        //{
                        //});
                        connection.InvokeAsync("Status", Hostname, sResult).Wait(1000);
                        Trace.WriteLine(" done.");
                        Program.MinimizeFootprint();
                    }
                    catch (Exception ex)
                    {
                        Trace.Write(DateTime.Now.ToString() + " ERROR: " + ex.Message);
                    }
                });

                connection.On <string>("version", (s1) =>
                {
                    try
                    {
                        Trace.Write(DateTime.Now.ToString() + "\t Get Version... ");
                        //Get File-Version
                        sScriptResult = (FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location)).FileVersion.ToString();
                        Trace.WriteLine(sScriptResult);

                        Random rnd       = new Random();
                        tReInit.Interval = rnd.Next(200, Properties.Settings.Default.StatusDelay); //wait max 5s to ReInit
                    }
                    catch (Exception ex)
                    {
                        Trace.Write(DateTime.Now.ToString() + " ERROR: " + ex.Message);
                    }
                });

                connection.On <string>("wol", (s1) =>
                {
                    try
                    {
                        if (!string.IsNullOrEmpty(s1))
                        {
                            foreach (string sMAC in s1.Split(';'))
                            {
                                try
                                {
                                    WOL.WakeUp(sMAC); //Send Broadcast

                                    //Send to local Gateway
                                    foreach (NetworkInterface f in NetworkInterface.GetAllNetworkInterfaces())
                                    {
                                        if (f.OperationalStatus == OperationalStatus.Up)
                                        {
                                            foreach (GatewayIPAddressInformation d in f.GetIPProperties().GatewayAddresses)
                                            {
                                                //Only use IPv4
                                                if (d.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                                                {
                                                    WOL.WakeUp(d.Address, 9, sMAC);
                                                }
                                            }
                                        }
                                    }
                                }
                                catch { }
                            }
                        }
                    }
                    catch { }
                });

                connection.On <string>("setinstance", (s1) =>
                {
                    Trace.WriteLine(DateTime.Now.ToString() + "\t Set instance: " + s1);
                    try
                    {
                        if (!string.IsNullOrEmpty(s1))
                        {
                            string sConfig  = Assembly.GetExecutingAssembly().Location + ".config";
                            XmlDocument doc = new XmlDocument();
                            doc.Load(sConfig);
                            doc.SelectSingleNode("/configuration/applicationSettings/DevCDRAgent.Properties.Settings/setting[@name='Instance']/value").InnerText = s1;
                            doc.Save(sConfig);
                            RestartService();

                            //Update Advanced Installer Persistent Properties
                            RegistryKey myKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Zander Tools\\{54F5CC06-300A-4DD4-94D9-0E18B2BE8DF1}", true);
                            if (myKey != null)
                            {
                                myKey.SetValue("INSTANCE", s1.Trim(), RegistryValueKind.String);
                                myKey.Close();
                            }
                        }
                    }
                    catch { }
                });

                connection.On <string>("setendpoint", (s1) =>
                {
                    Trace.WriteLine(DateTime.Now.ToString() + "\t Set Endpoint: " + s1);
                    try
                    {
                        if (!string.IsNullOrEmpty(s1))
                        {
                            if (s1.StartsWith("https://"))
                            {
                                string sConfig  = Assembly.GetExecutingAssembly().Location + ".config";
                                XmlDocument doc = new XmlDocument();
                                doc.Load(sConfig);
                                doc.SelectSingleNode("/configuration/applicationSettings/DevCDRAgent.Properties.Settings/setting[@name='Endpoint']/value").InnerText = s1;
                                doc.Save(sConfig);
                                RestartService();

                                //Update Advanced Installer Persistent Properties
                                RegistryKey myKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Zander Tools\\{54F5CC06-300A-4DD4-94D9-0E18B2BE8DF1}", true);
                                if (myKey != null)
                                {
                                    myKey.SetValue("ENDPOINT", s1.Trim(), RegistryValueKind.String);
                                    myKey.Close();
                                }
                            }
                        }
                    }
                    catch { }
                });

                connection.On <string>("setgroups", (s1) =>
                {
                    Trace.WriteLine(DateTime.Now.ToString() + "\t Set Groups: " + s1);
                    try
                    {
                        if (!string.IsNullOrEmpty(s1))
                        {
                            string sConfig  = Assembly.GetExecutingAssembly().Location + ".config";
                            XmlDocument doc = new XmlDocument();
                            doc.Load(sConfig);
                            doc.SelectSingleNode("/configuration/applicationSettings/DevCDRAgent.Properties.Settings/setting[@name='Groups']/value").InnerText = s1;
                            doc.Save(sConfig);

                            RestartService();

                            //Update Advanced Installer Persistent Properties
                            RegistryKey myKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Zander Tools\\{54F5CC06-300A-4DD4-94D9-0E18B2BE8DF1}", true);
                            if (myKey != null)
                            {
                                myKey.SetValue("GROUPS", s1.Trim(), RegistryValueKind.String);
                                myKey.Close();
                            }
                        }
                    }
                    catch { }
                });

                connection.On <string>("getgroups", (s1) =>
                {
                    try
                    {
                        if (!string.IsNullOrEmpty(s1))
                        {
                            sScriptResult = Properties.Settings.Default.Groups;

                            Random rnd       = new Random();
                            tReInit.Interval = rnd.Next(200, Properties.Settings.Default.StatusDelay); //wait max 5s to ReInit
                        }
                    }
                    catch { }
                });

                connection.On <string>("restartservice", (s1) =>
                {
                    try
                    {
                        RestartService();
                        sScriptResult = "restart Agent...";
                    }
                    catch { }
                });

                connection.On <string>("rzinstall", (s1) =>
                {
                    RZInst(s1);
                });

                connection.On <string>("rzupdate", (s1) =>
                {
                    var tSWScan = Task.Run(() =>
                    {
                        try
                        {
                            sScriptResult    = "Detecting RZ updates...";
                            Random rnd       = new Random();
                            tReInit.Interval = rnd.Next(200, Properties.Settings.Default.StatusDelay); //wait max 5s to ReInit

                            RZUpdater oUpdate = new RZUpdater();
                            RZScan oScan      = new RZScan(false, false);

                            oScan.GetSWRepository().Wait(30000);
                            oScan.SWScan().Wait(30000);
                            oScan.CheckUpdates(null).Wait(30000);

                            if (string.IsNullOrEmpty(s1))
                            {
                                sScriptResult    = oScan.NewSoftwareVersions.Count.ToString() + " RZ updates found";
                                rnd              = new Random();
                                tReInit.Interval = rnd.Next(200, Properties.Settings.Default.StatusDelay); //wait max 5s to ReInit
                            }

                            List <string> lSW = new List <string>();
                            foreach (var oSW in oScan.NewSoftwareVersions)
                            {
                                if (string.IsNullOrEmpty(s1) || s1 == "HUB")
                                {
                                    RZInst(oSW.Shortname);
                                }
                                else
                                {
                                    var SWList = s1.Split(';');
                                    if (SWList.Contains(oSW.Shortname))
                                    {
                                        RZInst(oSW.Shortname);
                                    }
                                }
                            }
                        }
                        catch { }
                    });
                });

                connection.On <string>("rzscan", (s1) =>
                {
                    var tSWScan = Task.Run(() =>
                    {
                        try
                        {
                            sScriptResult    = "Detecting updates...";
                            Random rnd       = new Random();
                            tReInit.Interval = rnd.Next(2000, Properties.Settings.Default.StatusDelay); //wait max 5s to ReInit

                            RZUpdater oUpdate = new RZUpdater();
                            RZScan oScan      = new RZScan(false, false);

                            oScan.GetSWRepository().Wait(30000);
                            oScan.SWScan().Wait(30000);
                            oScan.CheckUpdates(null).Wait(30000);

                            List <string> lSW = new List <string>();
                            foreach (var SW in oScan.NewSoftwareVersions)
                            {
                                lSW.Add(SW.Shortname + " " + SW.ProductVersion + " (old:" + SW.MSIProductID + ")");
                            }

                            sScriptResult    = JsonConvert.SerializeObject(lSW);
                            rnd              = new Random();
                            tReInit.Interval = rnd.Next(2000, Properties.Settings.Default.StatusDelay); //wait max 5s to ReInit
                        }
                        catch { }
                    });
                });

                connection.On <string>("inject", (s1) =>
                {
                    var tSWScan = Task.Run(() =>
                    {
                        try
                        {
                            sScriptResult = "Inject external code...";
                            try
                            {
                                ManagedInjection.Inject(s1);
                                sScriptResult = "External code executed.";
                            }
                            catch (Exception ex)
                            {
                                sScriptResult = "Injection error:" + ex.Message;
                            }
                        }
                        catch { }
                    });
                });

                connection.On <string, string>("userprocess", (cmd, arg) =>
                {
                    var tSWScan = Task.Run(() =>
                    {
                        if (string.IsNullOrEmpty(cmd))
                        {
                            cmd = Assembly.GetExecutingAssembly().Location;
                            arg = Environment.MachineName + ":" + "%USERNAME%";
                        }

                        try
                        {
                            if (string.IsNullOrEmpty(arg))
                            {
                                ProcessExtensions.StartProcessAsCurrentUser(cmd, null, null, false);
                            }
                            else
                            {
                                ProcessExtensions.StartProcessAsCurrentUser(null, cmd + " " + arg, null, false);
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    });
                });

                //connection.InvokeCoreAsync("Init", new object[] { Hostname }).Wait();
                connection.InvokeAsync("Init", Hostname).ContinueWith(task1 =>
                {
                    try
                    {
                        if (task1.IsFaulted)
                        {
                            Console.WriteLine("There was an error calling send: {0}", task1.Exception.GetBaseException());
                        }
                        else
                        {
                            try
                            {
                                foreach (string sGroup in Properties.Settings.Default.Groups.Split(';'))
                                {
                                    connection.InvokeAsync("JoinGroup", sGroup).ContinueWith(task2 =>
                                    {
                                    });
                                }
                                Program.MinimizeFootprint();
                            }
                            catch { }
                        }
                    }
                    catch { }
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine("There was an error: {0}", ex.Message);
            }
        }
    public void IListAddPropertyWithExistingName()
    {
      JProperty p1 = new JProperty("Test1", 1);
      JProperty p2 = new JProperty("Test2", "Two");
      IList l = new JObject(p1, p2);

      JProperty p3 = new JProperty("Test2", "II");

      l.Add(p3);
    }
    public void GenericListJTokenAdd()
    {
      JProperty p1 = new JProperty("Test1", 1);
      JProperty p2 = new JProperty("Test2", "Two");
      IList<JToken> l = new JObject(p1, p2);

      JProperty p3 = new JProperty("Test3", "III");

      l.Add(p3);

      Assert.AreEqual(3, l.Count);
      Assert.AreEqual(p3, l[2]);
    }
Example #31
0
        public ActionResult Export(string feedBillNum, string assemblyPartCode, string subAssemblyPartCode, string printStaus, string confirmStatus, DateTime beginDate, DateTime endDate)
        {
            string query = " 1=1 ";

            if (printStaus == "已打印")
            {
                query += " && PrintDate>=(\"" + beginDate + "\")&& PrintDate<=(\"" + endDate + "\")";
            }
            //query += " && FeedBillNum.Contains(\"" + feedBillNum + "\")&&WMS_Part.PartCode.Contains(\"" + assemblyPartCode + "\")";
            query += " && FeedBillNum.Contains(\"" + feedBillNum + "\")";
            query += " && WMS_Part.PartCode.Contains(\"" + subAssemblyPartCode + "\")&& PrintStaus.Contains(\"" + printStaus + "\")&& ConfirmStatus.Contains(\"" + confirmStatus + "\")";

            List <WMS_Feed_ListModel> list = m_BLL.GetListByWhere(ref setNoPagerAscById, query);
            JArray jObjects = new JArray();

            foreach (var item in list)
            {
                var jo = new JObject();
                //jo.Add("Id", item.Id);
                jo.Add("投料单号(业务)", item.FeedBillNum);
                //jo.Add("投料单号(系统)", item.ReleaseBillNum);
                jo.Add("投料物料", item.SubAssemblyPartCode);
                jo.Add("投料物料名称", item.SubAssemblyPartName);
                jo.Add("投料数量", item.FeedQty);
                jo.Add("箱数", item.BoxQty);
                jo.Add("体积", item.Capacity);
                jo.Add("批次号", item.Lot);
                jo.Add("备注", item.Remark);
                jo.Add("打印状态", item.PrintStaus);
                jo.Add("打印时间", item.PrintDate);
                //jo.Add("打印人", item.PrintMan);
                jo.Add("确认状态", item.ConfirmStatus);
                //jo.Add("确认人", item.ConfirmMan);
                jo.Add("确认时间", item.ConfirmDate);
                jo.Add("确认信息", item.ConfirmMessage);

                //jo.Add("投料部门", item.Department);
                //jo.Add("总成物料", item.AssemblyPartId);
                //jo.Add("库房", item.InvId);


                //jo.Add("Attr1", item.Attr1);
                //jo.Add("Attr2", item.Attr2);
                //jo.Add("Attr3", item.Attr3);
                //jo.Add("Attr4", item.Attr4);
                //jo.Add("Attr5", item.Attr5);
                //jo.Add("创建人", item.CreatePerson);
                //jo.Add("创建时间", item.CreateTime);
                //jo.Add("修改人", item.ModifyPerson);
                //jo.Add("修改时间", item.ModifyTime);
                jObjects.Add(jo);
            }
            var dt             = JsonConvert.DeserializeObject <DataTable>(jObjects.ToString());
            var exportFileName = string.Concat(
                RouteData.Values["controller"].ToString() + "_",
                DateTime.Now.ToString("yyyyMMddHHmmss"),
                ".xlsx");

            return(new ExportExcelResult
            {
                SheetName = "Sheet1",
                FileName = exportFileName,
                ExportData = dt
            });
        }
Example #32
0
        public static async Task SendGcm(string[] lines, Action <int, ErrorResult> onProgress, string authKey)
        {
            var jGcmData = new JObject();
            var jData    = new JObject();

            int i = 0;

            jData.Add("label", "nakup: " + DateTime.Now);
            foreach (string line in lines)
            {
                jData.Add("line" + i++, line);
            }

            jGcmData.Add("to", "/topics/shopList_" + StoreFactory.HalProxy.UserName);
            //jGcmData.Add("to", "/topics/global");
            jGcmData.Add("data", jData);

            var         url = new Uri("https://gcm-http.googleapis.com/gcm/send");
            ErrorResult res = new ErrorResult();

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));

                client.DefaultRequestHeaders.TryAddWithoutValidation(
                    "Authorization", "key=" + authKey);


                await Task.Factory.StartNew(() =>
                {
                    try
                    {
                        onProgress(0, new ErrorResult());
                        var task = client.PostAsync(url,
                                                    new StringContent(jGcmData.ToString(), Encoding.UTF8, "application/json"))
                                   .ContinueWith(response =>
                        {
                            if (response.IsCompleted && response.Result.StatusCode != System.Net.HttpStatusCode.OK)
                            {
                                onProgress(100, new ErrorResult((int)ErrorCodes.CommError, response.Result.ToString()));
                            }
                            else
                            {
                                onProgress(100, new ErrorResult((int)ErrorCodes.OK, "OK"));
                            }
                        });

                        int k = 0;
                        for (k = 0; k < 100 && !task.Wait(100); k++)
                        {
                            onProgress(k, new ErrorResult((int)ErrorCodes.OK, "Continue"));
                        }

                        if (k >= 100)
                        {
                            onProgress(100, new ErrorResult((int)ErrorCodes.CommError, "Timeout"));
                        }
                    }
                    catch (Exception ex)
                    {
                        onProgress(100, new ErrorResult(ex.HResult, "Unable to send GCM message: " + ex.Message));
                    }
                });
            }
        }
    public void IListAddBadValue()
    {
      JProperty p1 = new JProperty("Test1", 1);
      JProperty p2 = new JProperty("Test2", "Two");
      IList l = new JObject(p1, p2);

      l.Add("Bad!");
    }
Example #34
0
        public ActionResult ExportTemplate()
        {
            JArray jObjects = new JArray();
            var    jo       = new JObject();

            //jo.Add("Id", "");
            jo.Add("投料单号(业务)(必输)", "");
            //jo.Add("投料单号(系统)", "");
            jo.Add("投料部门", "");
            jo.Add("总成物料", "");
            jo.Add("投料物料(必输)", "");
            jo.Add("投料数量(必输)", "");
            jo.Add("箱数", "");
            jo.Add("体积", "");
            jo.Add("库房", "");
            jo.Add("批次号(格式:YYYY-MM-DD)", "");
            //jo.Add("子库存", "");
            jo.Add("备注", "");
            //jo.Add("打印状态", "");
            //jo.Add("打印时间", "");
            //jo.Add("打印人", "");
            //jo.Add("确认状态", "");
            //jo.Add("确认人", "");
            //jo.Add("确认时间", "");
            //jo.Add("Attr1", "");
            //jo.Add("Attr2", "");
            //jo.Add("Attr3", "");
            //jo.Add("Attr4", "");
            //jo.Add("Attr5", "");
            //jo.Add("创建人", "");
            //jo.Add("创建时间", "");
            //jo.Add("修改人", "");
            //jo.Add("修改时间", "");
            jo.Add("导入的错误信息", "");
            jObjects.Add(jo);
            var dt             = JsonConvert.DeserializeObject <DataTable>(jObjects.ToString());
            var exportFileName = string.Concat("投料单导入模板",
                                               ".xlsx");

            return(new ExportExcelResult
            {
                SheetName = "Sheet1",
                FileName = exportFileName,
                ExportData = dt
            });
        }
 public void DuplicatePropertyNameShouldThrow()
 {
   JObject o = new JObject();
   o.Add("PropertyNameValue", null);
   o.Add("PropertyNameValue", null);
 }
Example #36
0
        private static ZumoTest CreatePushTest(string wnsMethod, string nhNotificationType, JToken payload, XElement expectedResult, bool templatePush = false)
        {
            string testName      = "Test for " + wnsMethod + ": ";
            string payloadString = payload.ToString(Formatting.None);

            testName += payloadString.Length < 15 ? payloadString : (payloadString.Substring(0, 15) + "...");
            return(new ZumoTest(testName, async delegate(ZumoTest test)
            {
                test.AddLog("Test for method {0}, with payload {1}", wnsMethod, payload);
                var client = ZumoTestGlobals.Instance.Client;
                var table = client.GetTable(ZumoTestGlobals.PushTestTableName);

                // Workaround for multiple registration bug
                ZumoPushTests.pushesReceived.Clear();

                PushWatcher watcher = new PushWatcher();
                var item = new JObject();
                item.Add("method", wnsMethod);
                item.Add("channelUri", pushChannelUri);
                item.Add("payload", payload);
                item.Add("xmlPayload", expectedResult.ToString());
                item.Add("templateNotification", ZumoPushTestGlobals.TemplateNotification);
                if (ZumoTestGlobals.Instance.IsNHPushEnabled)
                {
                    item.Add("usingNH", true);
                    item.Add("nhNotificationType", nhNotificationType);
                }
                var pushResult = await table.InsertAsync(item);
                test.AddLog("Push result: {0}", pushResult);
                var notificationResult = await watcher.WaitForPush(TimeSpan.FromSeconds(10));
                if (notificationResult == null)
                {
                    test.AddLog("Error, push not received on the timeout allowed");
                    return false;
                }
                else
                {
                    test.AddLog("Push notification received:");
                    XElement receivedPushInfo = null;
                    switch (notificationResult.NotificationType)
                    {
                    case PushNotificationType.Raw:
                        if (nhNotificationType == "template")
                        {
                            receivedPushInfo = XElement.Parse(notificationResult.RawNotification.Content);
                        }
                        else
                        {
                            receivedPushInfo = new XElement("raw", new XText(notificationResult.RawNotification.Content));
                        }
                        break;

                    case PushNotificationType.Toast:
                        receivedPushInfo = XElement.Parse(notificationResult.ToastNotification.Content.GetXml());
                        break;

                    case PushNotificationType.Badge:
                        receivedPushInfo = XElement.Parse(notificationResult.BadgeNotification.Content.GetXml());
                        break;

                    case PushNotificationType.Tile:
                        receivedPushInfo = XElement.Parse(notificationResult.TileNotification.Content.GetXml());
                        break;
                    }

                    test.AddLog("  {0}: {1}", notificationResult.NotificationType, receivedPushInfo);

                    bool passed;
                    if (expectedResult.ToString(SaveOptions.DisableFormatting) == receivedPushInfo.ToString(SaveOptions.DisableFormatting))
                    {
                        test.AddLog("Received notification is the expected one.");
                        passed = true;
                    }
                    else
                    {
                        test.AddLog("Received notification is not the expected one. Expected:");
                        test.AddLog(expectedResult.ToString());
                        test.AddLog("Actual:");
                        test.AddLog(receivedPushInfo.ToString());
                        passed = false;
                    }

                    await Task.Delay(5000); // leave some time between pushes
                    return passed;
                }
            }, templatePush ? ZumoTestGlobals.RuntimeFeatureNames.NH_PUSH_ENABLED : ZumoTestGlobals.RuntimeFeatureNames.STRING_ID_TABLES));
        }
    public void GenericListJTokenAddBadToken()
    {
      JProperty p1 = new JProperty("Test1", 1);
      JProperty p2 = new JProperty("Test2", "Two");
      IList<JToken> l = new JObject(p1, p2);

      l.Add(new JValue("Bad!"));
    }
Example #38
0
        public void insertCustomer()
        {
            if (Login.jsonResult != null)
            {
                Cursor.Current = Cursors.WaitCursor;
                string token = "";
                foreach (var x in Login.jsonResult)
                {
                    if (x.Key.Equals("token"))
                    {
                        token = x.Value.ToString();
                    }
                }
                if (!token.Equals(""))
                {
                    var client = new RestClient(utilityc.URL);
                    client.Timeout = -1;
                    //string branch = (cmbBranch.Text.Equals("") || cmbBranch.Text == "All" ? "" : cmbBranch.Text);
                    var request = new RestRequest("/api/customer/new");
                    request.AddHeader("Authorization", "Bearer " + token);
                    request.Method = Method.POST;

                    JObject jObject  = new JObject();
                    JObject joHeader = new JObject();
                    joHeader.Add("code", (txtCode.Text == String.Empty ? null : txtCode.Text));
                    joHeader.Add("name", (txtName.Text == String.Empty ? null : txtName.Text));

                    int cust_id = 0;
                    foreach (DataRow row in dtCustomerTypes.Rows)
                    {
                        if (cmbCustomerType.Text == row["name"].ToString())
                        {
                            cust_id = Convert.ToInt32(row["id"].ToString());
                        }
                    }
                    joHeader.Add("cust_type", cust_id);

                    JArray jarrayDetails = new JArray();

                    for (int i = 0; i < dgv.Rows.Count; i++)
                    {
                        JObject joDetails = new JObject();

                        string firstName      = dgv.Rows[i].Cells["first_name"].Value.ToString(),
                               middleName     = dgv.Rows[i].Cells["middle_initial"].Value.ToString(),
                               lastName       = dgv.Rows[i].Cells["last_name"].Value.ToString(),
                               birthDate      = dgv.Rows[i].Cells["birthdate"].Value.ToString(),
                               landLineNumber = dgv.Rows[i].Cells["landline_number"].Value.ToString(),
                               mobileNumber   = dgv.Rows[i].Cells["mobile_number"].Value.ToString(),
                               aDdress        = dgv.Rows[i].Cells["address"].Value.ToString(),
                               emailAddress   = dgv.Rows[i].Cells["email_address"].Value.ToString();

                        joDetails.Add("first_name", firstName);
                        joDetails.Add("middle_initial", middleName);
                        joDetails.Add("last_name", lastName);
                        joDetails.Add("birthdate", birthDate);
                        joDetails.Add("landline_number", landLineNumber);
                        joDetails.Add("mobile_number", mobileNumber);
                        joDetails.Add("address", aDdress);
                        joDetails.Add("email", emailAddress);
                        jarrayDetails.Add(joDetails);
                    }
                    jObject.Add("header", joHeader);
                    jObject.Add("details", jarrayDetails);

                    Console.WriteLine(jObject);
                    request.AddParameter("application/json", jObject, ParameterType.RequestBody);
                    var response = client.Execute(request);
                    if (response.ErrorMessage == null)
                    {
                        if (response.Content.Substring(0, 1).Equals("{"))
                        {
                            jObject = JObject.Parse(response.Content.ToString());
                            bool isSuccess = false;

                            string msg = "No message response found";
                            foreach (var x in jObject)
                            {
                                if (x.Key.Equals("message"))
                                {
                                    msg = x.Value.ToString();
                                }
                            }

                            foreach (var x in jObject)
                            {
                                if (x.Key.Equals("success"))
                                {
                                    isSuccess = Convert.ToBoolean(x.Value.ToString());
                                    txtCode.Clear();
                                    txtName.Clear();
                                    isSubmit = true;
                                    MessageBox.Show(msg, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    txtCode.Clear();
                                    txtName.Clear();
                                    cmbCustomerType.SelectedIndex = -1;
                                    this.Dispose();
                                }
                            }

                            if (!isSuccess)
                            {
                                if (msg.Equals("Token is invalid"))
                                {
                                    MessageBox.Show("Your login session is expired. Please login again", "Validation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                }
                                else
                                {
                                    MessageBox.Show(msg, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                }
                            }
                        }
                        else
                        {
                            MessageBox.Show(response.Content.ToString(), "Validation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                    else
                    {
                        MessageBox.Show(response.ErrorMessage, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    Cursor.Current = Cursors.Default;
                }
            }
        }
Example #39
0
        public void ListChanged()
        {
            JProperty p1 = new JProperty("Test1", 1);
            JProperty p2 = new JProperty("Test2", "Two");
            var o = new JObject(p1, p2);

            ListChangedType? changedType = null;
            int? index = null;

            o.ListChanged += (s, a) =>
            {
                changedType = a.ListChangedType;
                index = a.NewIndex;
            };

            JProperty p3 = new JProperty("Test3", "III");

            o.Add(p3);
            Assert.Equal(changedType, ListChangedType.ItemAdded);
            Assert.Equal(index, 2);
            Assert.Equal(p3, ((IList<JToken>)o)[index.Value]);

            JProperty p4 = new JProperty("Test4", "IV");

            ((IList<JToken>)o)[index.Value] = p4;
            Assert.Equal(changedType, ListChangedType.ItemChanged);
            Assert.Equal(index, 2);
            Assert.Equal(p4, ((IList<JToken>)o)[index.Value]);
            Assert.False(((IList<JToken>)o).Contains(p3));
            Assert.True(((IList<JToken>)o).Contains(p4));

            o["Test1"] = 2;
            Assert.Equal(changedType, ListChangedType.ItemChanged);
            Assert.Equal(index, 0);
            Assert.Equal(2, (int)o["Test1"]);
        }
Example #40
0
        //Perform a job at startup and at every caching event
        private void DoMyWork()
        {
            //read data from databases and store them in global Data.
            IEnumerable <Student>            student  = Helpers.GetAllStudent();
            IEnumerable <FacStaff>           facstaff = Helpers.GetAllFacultyStaff();
            IEnumerable <Alumni>             alumni   = Helpers.GetAllAlumni();
            IEnumerable <BasicInfoViewModel> basic    = Helpers.GetAllBasicInfoExcludeAlumni();

            JObject publicStudent = Helpers.GetAllPublicStudents();
            IEnumerable <PublicFacultyStaffProfileViewModel> publicFacStaff = Helpers.GetAllPublicFacultyStaff();
            IEnumerable <PublicAlumniProfileViewModel>       publicAlumni   = Helpers.GetAllPublicAlumni();
            IList <JObject> allPublicAccounts = new List <JObject>();
            IList <JObject> allPublicAccountsWithoutAlumni          = new List <JObject>();
            IList <JObject> allPublicAccountsWithoutCurrentStudents = new List <JObject>();

            // storing in global variab
            Data.StudentData       = student;
            Data.PublicStudentData = publicStudent;

            Data.FacultyStaffData       = facstaff;
            Data.PublicFacultyStaffData = publicFacStaff;

            Data.AlumniData                = alumni;
            Data.PublicAlumniData          = publicAlumni;
            Data.AllBasicInfoWithoutAlumni = basic;

            foreach (JToken aStudent in Data.PublicStudentData.SelectToken("Students"))
            {
                if (aStudent == null)
                {
                    break;
                }
                JObject theStu = JObject.FromObject(aStudent);
                theStu.Add("Type", "Student");
                theStu.Add("BuildingDescription", null);
                theStu.Add("OnCampusDepartment", null);
                allPublicAccounts.Add(theStu);
                allPublicAccountsWithoutAlumni.Add(theStu);
            }

            foreach (PublicFacultyStaffProfileViewModel aFacStaff in Data.PublicFacultyStaffData)
            {
                JObject theFacStaff = JObject.FromObject(aFacStaff);
                theFacStaff.Add("Hall", null);
                theFacStaff.Add("Mail_Location", null);
                theFacStaff.Add("Class", null);
                theFacStaff.Add("Major1Description", null);
                theFacStaff.Add("Major2Description", null);
                theFacStaff.Add("Major3Description", null);
                theFacStaff.Add("Minor1Description", null);
                theFacStaff.Add("Minor2Description", null);
                theFacStaff.Add("Minor3Description", null);
                allPublicAccounts.Add(JObject.FromObject(theFacStaff));
                allPublicAccountsWithoutAlumni.Add(JObject.FromObject(theFacStaff));
                allPublicAccountsWithoutCurrentStudents.Add(JObject.FromObject(theFacStaff));
            }
            foreach (PublicAlumniProfileViewModel anAlum in Data.PublicAlumniData)
            {
                JObject theAlum = JObject.FromObject(anAlum);
                theAlum.Add("Type", "Alum");
                theAlum.Add("BuildingDescription", null);
                theAlum.Add("Hall", null);
                theAlum.Add("Mail_Location", null);
                theAlum.Add("OnCampusDepartment", null);
                theAlum.Add("Class", null);
                theAlum.Add("Major3Description", null);
                theAlum.Add("Minor1Description", null);
                theAlum.Add("Minor2Description", null);
                theAlum.Add("Minor3Description", null);
                allPublicAccounts.Add(theAlum);
                allPublicAccountsWithoutCurrentStudents.Add(theAlum);
            }
            Data.AllPublicAccountsWithoutCurrentStudents = allPublicAccountsWithoutCurrentStudents;
            Data.AllPublicAccounts = allPublicAccounts;
            Data.AllPublicAccountsWithoutAlumni = allPublicAccountsWithoutAlumni;
        }
Example #41
0
        public void GenericDictionaryAdd()
        {
            var o = new JObject();

            o.Add("PropertyNameValue", new JValue(1));
            Assert.Equal(1, (int)o["PropertyNameValue"]);

            o.Add("PropertyNameValue1", null);
            Assert.Equal(null, ((JValue)o["PropertyNameValue1"]).Value);

            Assert.Equal(2, o.Children().Count());
        }
Example #42
0
        public JObject ObjectToJson(Habitacion entidad)
        {
            JObject objJson = new JObject();

            objJson.Add("m_id", entidad.Id);
            if (entidad.Ref != null)
            {
                objJson.Add("m_ref", entidad.Ref);
            }
            objJson.Add("m_version", entidad.Version);
            objJson.Add("vigente", GetStringFromBool(entidad.IsDeleted == false));

            objJson.Add("proveedor_id", entidad.ProveedorId);
            objJson.Add("numero_habitacion", entidad.NumeroHabitacion);
            objJson.Add("tipo_habitacion_id", entidad.TipoHabitacionId);
            objJson.Add("capacidad", entidad.Capacidad);
            objJson.Add("estado", entidad.Estado ? true : false);
            objJson.Add("aprobado", entidad.Aprobado ? true : false);
            objJson.Add("fecha_aprobacion", GetStringFromDate(entidad.FechaAprobacion));
            objJson.Add("creation_time", GetStringFromDateTime(entidad.CreationTime));
            objJson.Add("creator_user_id", entidad.CreatorUserId);
            return(objJson);
        }
Example #43
0
        public void GenericCollectionClear()
        {
            var o = new JObject();
            o.Add("PropertyNameValue", new JValue(1));
            Assert.Equal(1, o.Children().Count());

            JProperty p = (JProperty)o.Children().ElementAt(0);

            ((ICollection<KeyValuePair<string, JToken>>)o).Clear();
            Assert.Equal(0, o.Children().Count());

            Assert.Equal(null, p.Parent);
        }
 /// <summary>
 /// Adds a child node to the root structure with the specified name.
 /// </summary>
 /// <param name="name"></param>
 public void AddChild(string name)
 {
     data.Add(name, new JObject());
 }
Example #45
0
        public void GenericDictionaryContains()
        {
            var o = new JObject();
            o.Add("PropertyNameValue", new JValue(1));
            Assert.Equal(1, o.Children().Count());

            bool contains = ((IDictionary<string, JToken>)o).ContainsKey("PropertyNameValue");
            Assert.Equal(true, contains);
        }
Example #46
0
        public static int InstallCommand(Config config)
        {   
            var asmDiffPath = Path.Combine(config.JitDasmRoot, "asmdiff.json");
            string configJson = File.ReadAllText(asmDiffPath);
            string tag = String.Format("{0}-{1}", config.JobName, config.Number);
            string toolPath = Path.Combine(config.JitDasmRoot, "tools", tag);
            var jObj = JObject.Parse(configJson);
            var tools = (JArray)jObj["tools"];
            int ret = 0;

            // Early out if the tool is already installed.
            if (tools.Where(x => (string)x["tag"] == tag).Any())
            {
                Console.WriteLine("{0} is already installed in the asmdiff.json. Remove before re-install.", tag);
                return -1;
            }

            // Issue cijobs command to download bits            
            List<string> cijobsArgs = new List<string>();

            cijobsArgs.Add("copy");

            // Set up job name
            cijobsArgs.Add("--job");
            cijobsArgs.Add(config.JobName);
            
            if (config.BranchName != null)
            {
                cijobsArgs.Add("--branch");
                cijobsArgs.Add(config.BranchName);
                
            }
            
            if (config.DoLastSucessful)
            {
                cijobsArgs.Add("--last_successful");
            }
            else
            {
                // Set up job number
                cijobsArgs.Add("--number");
                cijobsArgs.Add(config.Number);
            }
            
            cijobsArgs.Add("--unzip");
            
            cijobsArgs.Add("--output");
            cijobsArgs.Add(toolPath);

            if (config.Verbose)
            {
                Console.WriteLine("ci command: {0} {1}", "cijobs", String.Join(" ", cijobsArgs));
            }
            
            Command cijobsCmd =  Command.Create("cijobs", cijobsArgs);

            // Wireup stdout/stderr so we can see outout.
            cijobsCmd.ForwardStdOut();
            cijobsCmd.ForwardStdErr();

            CommandResult result = cijobsCmd.Execute();

            if (result.ExitCode != 0)
            {
                Console.WriteLine("cijobs command returned with {0} failures", result.ExitCode);
                return result.ExitCode;
            }

            JObject newTool = new JObject();
            newTool.Add("tag", tag);
            // Derive underlying tool directory based on current RID.
            string[] platStrings = config.RID.Split('.');
            string platformPath = Path.Combine(toolPath, "Product");
            foreach (var dir in Directory.EnumerateDirectories(platformPath))
            {
                if (Path.GetFileName(dir).ToUpper().Contains(platStrings[0].ToUpper()))
                {
                    newTool.Add("path", Path.GetFullPath(dir));
                    tools.Last.AddAfterSelf(newTool);
                    break;
                }
            }

            // Overwrite current asmdiff.json with new data.
            using (var file = File.CreateText(asmDiffPath))
            {
                using (JsonTextWriter writer = new JsonTextWriter(file))
                {
                    writer.Formatting = Formatting.Indented;
                    jObj.WriteTo(writer);
                }
            }
            return ret;
        }
Example #47
0
        public void GenericCollectionCopyToInsufficientArrayCapacity()
        {
            AssertException.Throws<ArgumentException>(() =>
            {
                var o = new JObject();
                o.Add("PropertyNameValue", new JValue(1));
                o.Add("PropertyNameValue2", new JValue(2));
                o.Add("PropertyNameValue3", new JValue(3));

                ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[3], 1);
            }, @"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array.");
        }
Example #48
0
        public void Index(Boolean store = true, Boolean phonemes = true, string name = "", int start = 1880, int end = 2017, double cutoff = 0, double min = 0)
        {
            JObject       result = new JObject();
            List <string> dataId = new List <string>();

            if (store) // 使用roster文件读取json
            {
                JArray                 totals;
                List <dynamic>         data             = new List <dynamic>(); // 储存json文件里的数据
                string                 totalsJsonFile   = "C:/Users/Administrator/Desktop/babynames/flat/roster/roster.json";
                System.IO.StreamReader totalsJsonReader = System.IO.File.OpenText(totalsJsonFile);
                using (JsonTextReader reader = new JsonTextReader(totalsJsonReader))
                {
                    totals = (JArray)JToken.ReadFrom(reader); // 将totals文件转换成JObject类型
                }
                foreach (string i in totals)
                {
                    dataId.Add(i);
                    // i 为文件的name 根据i去读取文件
                    JObject dataSingleJson;             // 保存每个小文件的json
                    string  cmud     = CmuDictAsync(i); // 获取每个名称的音素
                    string  jsonFile = "C:/Users/Administrator/Desktop/babynames/flat/" + i + ".json";
                    System.IO.StreamReader jsonFileReader = System.IO.File.OpenText(jsonFile);
                    using (JsonTextReader singleReader = new JsonTextReader(jsonFileReader))
                    {
                        dataSingleJson = (JObject)JToken.ReadFrom(singleReader); // 将totals文件转换成JObject类型
                        result.Add(i, dataSingleJson);
                    }
                }
            }
            else
            {
                List <dynamic> filesTxt = new List <dynamic>();

                filesTxt = loadData(start, end); // 使用txt读取转成json
                if (name != "")
                {
                    filesTxt = filesTxt.Where(p => p["names"]["name"] == name).ToList(); // 只截取name的数据
                }
                JObject data = new JObject();
                string  id, KValues;
                int     VValues;
                decimal PValues;
                JObject nullData = new JObject();
                JObject nodePercents, nodeValues;
                int     filesCount = filesTxt.Count; // 单独写出来提升循环速度

                for (int i = 0; i < filesCount; i++) // 倒叙提升速度
                {
                    var filesList = filesTxt[i]["names"];
                    id = filesList["name"] + "-" + filesList["gender"];
                    if (!dataId.Contains(id)) // 不存在id的时候新增一条数据
                    {
                        KValues = Convert.ToString(filesTxt[i]["year"]);
                        VValues = filesTxt[i]["names"]["value"];
                        PValues = filesTxt[i]["percent"];
                        dataId.Add(id);
                        data.Add("_id", id);
                        data.Add("name", filesList["name"]);
                        data.Add("gender", filesList["gender"]);
                        data.Add("values", new JObject(new JProperty(KValues, new JValue(VValues))));
                        data.Add("percents", new JObject(new JProperty(KValues, new JValue(PValues))));
                        data.Add("normalized", nullData);
                        result.Add(id, data);
                        data = new JObject();
                        continue;
                    }
                    // 在把新的数据加进去
                    nodePercents = result[id].SelectToken("percents") as JObject;
                    nodePercents.Add(new JProperty(Convert.ToString(filesTxt[i]["year"]), filesTxt[i]["percent"]));      // 在percents下面新增数据
                    nodeValues = result[id].SelectToken("values") as JObject;
                    nodeValues.Add(new JProperty(Convert.ToString(filesTxt[i]["year"]), filesTxt[i]["names"]["value"])); // 同理
                }
            }
            string path;

            if (!store)
            {
                path = "C:/Users/Administrator/Desktop/babynames/flatTemp"; // 读取txt转json保存的文件夹
            }
            else
            {
                path = "C:/Users/Administrator/Desktop/babynames/data"; //读取json 保存的文件夹
            }
            // 生成音律文件
            if (phonemes)
            {
                JObject phonemesResult     = new JObject();
                JObject tempPhonemesResult = (JObject)result.DeepClone(); // 将result 复制一份,因为接下来的Peaks和Pronunciation会改变result,DeepClone()为深拷贝,简单的赋值依旧会改变result

                Pronunciation(Peaks(tempPhonemesResult));                 // 去计算获取pronunciation属性的值和peaks属性的值
                foreach (var i in tempPhonemesResult)                     // 遍历最后的结果,写入json文件中
                {
                    dynamic isHavePronunciation = i.Value["pronunciation"];
                    var     phoneme             = i.Value["pronunciation"].ToString().Split(new char[2] {
                        ' ', ' '
                    });

                    if (isHavePronunciation == null) // 如果这个名字没有音素直接跳过
                    {
                        continue;
                    }
                    else
                    {
                        if (phonemesResult[phoneme[0]] == null) //如果不存在初始化文件格式
                        {
                            JObject tempData = new JObject();
                            tempData.Add("percents", new JObject());
                            tempData.Add("names", new JArray());
                            phonemesResult.Add(phoneme[0], tempData);
                        }
                    }
                    JObject tempNames = new JObject();
                    tempNames.Add("name", i.Value["name"]);
                    tempNames.Add("peak", MapValue(i.Value["peaks"]["percents"]["percents"]));
                    JArray phonemesNames = phonemesResult[phoneme[0]].SelectToken("names") as JArray;
                    phonemesNames.Add(tempNames);         // 往names下面填写name,peak属性值

                    for (var y = start; y <= end; y += 1) // 找出这个音素下所有名称对应的percents值,如果这个音素有这一年的值直接累加,若没有则新增
                    {
                        JObject JPercents   = phonemesResult[phoneme[0]].SelectToken("percents") as JObject;
                        decimal tempDecimal = 0;

                        if (!JPercents.ContainsKey(y.ToString())) // 不存在就 新增
                        {
                            tempDecimal  = 0;
                            tempDecimal += Convert.ToDecimal(i.Value["percents"].SelectToken(y.ToString()));
                            JPercents.Add(y.ToString(), tempDecimal);
                        }
                        else // 存在就累加
                        {
                            tempDecimal  = Convert.ToDecimal(JPercents.GetValue(y.ToString()));
                            tempDecimal += Convert.ToDecimal(i.Value["percents"].SelectToken(y.ToString())); // 取出相同年份的值进行叠加
                            JPercents.SelectToken(y.ToString()).Replace(tempDecimal);                        // 替换指定年份的值
                        }
                    }
                }
                // 将操作完成后的数据生成json文件
                JArray data = new JArray();
                foreach (var d in phonemesResult)
                {
                    JObject temp = new JObject();

                    temp.Add("phoneme", d.Key);

                    JArray array     = JArray.Parse(d.Value["names"].ToString());
                    JArray sorted    = new JArray(array.OrderByDescending(obj => obj["peak"])); // 按照peak降序,将peak最大的名字放在第一位
                    JArray namesList = new JArray();
                    foreach (var p in sorted)
                    {
                        namesList.Add(p["name"].ToString()); // 依次添加进去
                    }
                    temp.Add("names", namesList);

                    JObject arrayPercents  = JObject.Parse(d.Value["percents"].ToString());
                    JObject sortedPercents = new JObject(arrayPercents.Properties().Where(p => (decimal)p.Value != 0)); // 按照peak降序,将peak最大的名字放在第一位

                    JArray  jArray       = new JArray();
                    JObject tempPercents = new JObject();
                    foreach (var pe in sortedPercents)
                    {
                        tempPercents.Add("key", pe.Key);
                        tempPercents.Add("value", pe.Value);
                        jArray.Add(tempPercents);
                        tempPercents = new JObject();
                    }
                    temp.Add("percents", jArray);
                    data.Add(temp);
                    temp = new JObject();
                }
                string pathPhonemes     = path + "/roster";
                string fileNamePhonemes = "/phonemes.json";// 生成phonemes文件
                FileStr(pathPhonemes, fileNamePhonemes, data, true);
            }

            // 获取至少出来了多少年的名字
            if (cutoff != 0)
            {
                int     allYearCount = 0;
                JObject tempResult   = new JObject(result); // 因为下面要修改result 所有这里将要遍历的数据放在一个临时文件中
                foreach (var i in tempResult)
                {
                    JToken json = i.Value;
                    foreach (JProperty JP in json)
                    {
                        if (JP.Name == "values")             // 只查找key值为values
                        {
                            allYearCount = JP.Value.Count(); // 长度即为该名称出现的年份次数
                            if (allYearCount < cutoff)       // 小于给定的cutoff移除
                            {
                                result.Remove(i.Key);        // 移除不符合条件的数据
                            }
                        }
                    }
                }
            }
            // 获取在一年内至少出现多少次的名字
            if (min != 0)
            {
                JObject minResult = new JObject();
                foreach (var i in result)
                {
                    JToken json = i.Value;
                    foreach (JProperty JP in json)
                    {
                        if (JP.Name == "values") // 只查找key值为values
                        {
                            foreach (int m in JP.Value)
                            {
                                if (m >= min)
                                {
                                    minResult.Add(i.Key, i.Value); break; // 将符合条件的数据新增等minResult中
                                }
                            }
                        }
                    }
                }
                result = minResult;   // 替换原来的result文件
            }
            foreach (var i in result) // 遍历最后的结果,写入json文件中
            {
                string singleFileName = "/" + i.Key + ".json";
                JToken json           = i.Value;
                FileStr(path, singleFileName, json); // 生成json文件
            }

            // 生成phonemes文件代码


            // 生成roster的代码
            path = path + "/roster";
            string fileName = "/roster.json";// 生成roster文件

            FileStr(path, fileName, dataId);
            string        fileName_short = "/roster_short.json"; // 生成roster_short文件,此文件包含姓名即有男又有女
            List <string> roster_short   = new List <string>();

            foreach (string i in dataId)
            {
                string SingleName   = i.Split('-')[0].ToString();
                string SingleGender = i.Split('-')[1].ToString();
                if (SingleGender == "F")
                {
                    if (dataId.IndexOf(SingleName + "-M") != -1)
                    {
                        roster_short.Add(SingleName + " (F)");
                    }
                    else
                    {
                        roster_short.Add(SingleName);
                    }
                }
                else
                {
                    if (dataId.IndexOf(SingleName + "-F") != -1)
                    {
                        roster_short.Add(SingleName + " (M)");
                    }
                    else
                    {
                        roster_short.Add(SingleName);
                    }
                }
            }
            FileStr(path, fileName_short, roster_short);
        }
Example #49
0
        public void KeyValuePairIterate()
        {
            var o = new JObject();
            o.Add("PropertyNameValue1", new JValue(1));
            o.Add("PropertyNameValue2", new JValue(2));

            int i = 1;
            foreach (KeyValuePair<string, JToken> pair in o)
            {
                Assert.Equal("PropertyNameValue" + i, pair.Key);
                Assert.Equal(i, (int)pair.Value);

                i++;
            }
        }
Example #50
0
        private JArray GetExportData()
        {
            List <Spl_PersonModel> list = m_BLL.GetList(ref setNoPagerAscById, "");
            JArray jObjects             = new JArray();

            foreach (var item in list)
            {
                var jo = new JObject();
                jo.Add("Id", item.Id);
                jo.Add("Name", item.Name);
                jo.Add("Sex", item.Sex);
                jo.Add("Age", item.Age);
                jo.Add("IDCard", item.IDCard);
                jo.Add("Phone", item.Phone);
                jo.Add("Email", item.Email);
                jo.Add("Address", item.Address);
                jo.Add("CreateTime", item.CreateTime);
                jo.Add("Region", item.Region);
                jo.Add("Category", item.Category);
                jObjects.Add(jo);
            }
            return(jObjects);
        }
Example #51
0
        public void IListAdd()
        {
            JProperty p1 = new JProperty("Test1", 1);
            JProperty p2 = new JProperty("Test2", "Two");
            IList l = new JObject(p1, p2);

            JProperty p3 = new JProperty("Test3", "III");

            l.Add(p3);

            Assert.Equal(3, l.Count);
            Assert.Equal(p3, l[2]);
        }
        static void Main(string[] args)
        {
            MqttFactory factory = new MqttFactory();

            mqttClient = factory.CreateMqttClient();

            if ((args.Length != 3))
            {
                Console.WriteLine("[MQTT Server] [UserName] [ClientID]");
                Console.WriteLine("Press <enter> to exit");
                Console.ReadLine();
                return;
            }

            server   = args[0];
            username = args[1];
            deviceID = args[2];

            Console.WriteLine($"MQTT Server:{server} DeviceID:{deviceID}");

            // AllThingsTalk formatted device state update topic
            string topicD2C = $"device/{deviceID}/state";

            mqttOptions = new MqttClientOptionsBuilder()
                          .WithTcpServer(server)
                          .WithCredentials(username, "HighlySecurePassword")
                          .WithClientId(deviceID)
                          .WithTls()
                          .Build();

            mqttClient.UseDisconnectedHandler(new MqttClientDisconnectedHandlerDelegate(e => MqttClient_Disconnected(e)));
            mqttClient.UseApplicationMessageReceivedHandler(new MqttApplicationMessageReceivedHandlerDelegate(e => MqttClient_ApplicationMessageReceived(e)));
            mqttClient.ConnectAsync(mqttOptions).Wait();

            // AllThingsTalk formatted device command with wildcard topic
            string topicC2D = $"device/{deviceID}/asset/+/command";

            mqttClient.SubscribeAsync(topicC2D, MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce).GetAwaiter().GetResult();

            while (true)
            {
                JObject payloadJObject = new JObject();

                double temperature = 22.0 + (DateTime.UtcNow.Millisecond / 1000.0);
                temperature = Math.Round(temperature, 1);
                double humidity = 50 + (DateTime.UtcNow.Millisecond / 100.0);
                humidity = Math.Round(humidity, 1);

                JObject temperatureJObject = new JObject
                {
                    { "value", temperature }
                };
                payloadJObject.Add("Temperature", temperatureJObject);

                JObject humidityJObject = new JObject
                {
                    { "value", humidity }
                };
                payloadJObject.Add("Humidity", humidityJObject);

                string payload = JsonConvert.SerializeObject(payloadJObject);
                Console.WriteLine($"Topic:{topicD2C} Payload:{payload}");

                var message = new MqttApplicationMessageBuilder()
                              .WithTopic(topicD2C)
                              .WithPayload(payload)
                              .WithAtMostOnceQoS()
//					.WithAtLeastOnceQoS()
                              .Build();

                Console.WriteLine("PublishAsync start");
                mqttClient.PublishAsync(message).Wait();
                Console.WriteLine("PublishAsync finish");

                Thread.Sleep(15100);
            }
        }
Example #53
0
        public void IListAddBadValue()
        {
            AssertException.Throws<ArgumentException>(() =>
            {
                JProperty p1 = new JProperty("Test1", 1);
                JProperty p2 = new JProperty("Test2", "Two");
                IList l = new JObject(p1, p2);

                l.Add("Bad!");
            }, "Argument is not a JToken.");
        }
        private string ParseSchemaDefinitions(RedoxJsonSchema rs)
        {
            string tokenName;
            string typeName;
            string error;

            try
            {
                JObject   tokenItems;
                JToken    token;
                JProperty tokenParent;
                var       sroot       = new JObject();
                var       objs        = sroot.Descendants();
                var       comparer    = new JTokenEqualityComparer();
                var       objectToken = JToken.FromObject("object");
                sroot = rs.Schema;
                objs  = sroot.Descendants()
                        .OfType <JObject>()
                        .Where(t => comparer.Equals(t["type"], objectToken))
                        .ToList();
                foreach (JObject o in objs)
                {
                    AllObjects.Add(o);
                    tokenParent = (JProperty)o.Parent;
                    tokenName   = tokenParent.Name;
                    if (tokenName == "items")
                    {
                        continue;
                    }
                    token = o;
                    if (!IsSimpleObject(o, out error))
                    {
                        continue;
                    }
                    if (!string.IsNullOrEmpty(error))
                    {
                        return(error);
                    }
                    if (!ObjectTypeDict.ContainsKey(tokenName))
                    {
                        ObjectTypeDict.Add(tokenName, token.Parent.ToString());
                        token["title"] = tokenName;
                        defs.Add(new JProperty(tokenName, token));
                    }
                    else if (!ObjectTypeDict.ContainsValue(token.Parent.ToString()))
                    {
                        tokenName = GetNewName(tokenName, ObjectTypeDict);
                        ObjectTypeDict.Add(tokenName, token.Parent.ToString());
                        token["title"] = tokenName;
                        defs.Add(new JProperty(tokenName, token));
                    }
                    else
                    {
                        token["title"] = tokenName;
                    }
                }
                var arrayToken = JToken.FromObject("array");
                var arrObjs    = sroot.Descendants()
                                 .OfType <JObject>()
                                 .Where(t => comparer.Equals(t["type"], arrayToken))
                                 .ToList();
                foreach (JToken a in arrObjs)
                {
                    tokenName  = ((JProperty)a.Parent).Name;
                    tokenItems = (JObject)a["items"];
                    typeName   = tokenName + "Item";
                    if (!ObjectTypeDict.ContainsKey(typeName))
                    {
                        if (IsSimpleObject(tokenItems, out error))
                        {
                            defs.Add(new JProperty(typeName, tokenItems));
                            ObjectTypeDict.Add(typeName, tokenItems.Parent.ToString());
                        }
                        if (!string.IsNullOrEmpty(error))
                        {
                            return(error);
                        }
                        tokenItems["title"] = typeName;
                    }
                    else if (!ObjectTypeDict.ContainsValue(tokenItems.Parent.ToString()))
                    {
                        typeName = GetNewName(typeName, ObjectTypeDict);
                        if (IsSimpleObject(tokenItems, out error))
                        {
                            defs.Add(new JProperty(typeName, tokenItems));
                            ObjectTypeDict.Add(typeName, tokenItems.Parent.ToString());
                        }
                        if (!string.IsNullOrEmpty(error))
                        {
                            return(error);
                        }
                        tokenItems["title"] = typeName;
                    }
                    else
                    {
                        tokenItems["title"] = typeName;
                    }
                }
                foreach (JObject o in objs)
                {
                    tokenParent = (JProperty)o.Parent;
                    tokenName   = tokenParent.Name;
                    if (tokenName == "items")
                    {
                        continue;
                    }
                    if (!IsSimpleObject(o, out error))
                    {
                        if (!string.IsNullOrEmpty(error))
                        {
                            return(error);
                        }
                        if (!ComplexObjectDict.ContainsKey(tokenName) && !ObjectTypeDict.ContainsKey(tokenName))
                        {
                            if (ComplexObjectDict.ContainsValue(o.Parent.ToString()))
                            {
                                tokenName = GetNewName(tokenName, ComplexObjectDict);
                            }
                            ComplexObjectDict.Add(tokenName, o.Parent.ToString());
                            ComplexObjectLists.Add(tokenName, new List <JObject>());
                            ComplexObjectLists[tokenName].Add(o);
                        }
                        else
                        {
                            if (ComplexObjectDict.ContainsValue(o.Parent.ToString()))
                            {
                                if (ComplexObjectLists[tokenName] == null)
                                {
                                    ComplexObjectLists[tokenName] = new List <JObject>();
                                }
                                ComplexObjectLists[tokenName].Add(o);
                            }
                            else
                            {
                                tokenName = GetNewName(tokenName, ComplexObjectDict);
                                ComplexObjectDict.Add(tokenName, o.Parent.ToString());
                                ComplexObjectLists.Add(tokenName, new List <JObject>());
                                ComplexObjectLists[tokenName].Add(o);
                            }
                        }
                        o["title"] = tokenName;
                    }
                    if (!string.IsNullOrEmpty(error))
                    {
                        return(error);
                    }
                }
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
            return("");
        }
Example #55
0
 public void AddValueToObject()
 {
   JObject o = new JObject();
   o.Add(5);
 }
 public virtual void Serialize(JObject json)
 {
     json?.Add("BackupPath", BackupPath);
     json?.Add("FirstRun", FirstRun);
     json?.Add("Incremental", Incremental);
 }
        public static JContainer ToJContainer(this XElement target)
        {
            if (target != null)
            {
                var jobj = new JObject();

                foreach (var attr in target.Attributes())
                {
                    jobj.Add(new JProperty(string.Concat('@', attr.Name.LocalName), attr.Value));
                }

                var textNodes = target.Nodes().OfType<XText>();

                foreach (var node in textNodes)
                {
                    string name;
                    switch (node.NodeType)
                    {
                        case System.Xml.XmlNodeType.CDATA:
                            name = "#cdata-section";
                            break;
                        case System.Xml.XmlNodeType.Text:
                            name = "#text";
                            break;
                        default:
                            name = "#other";
                            break;
                    }

                    jobj.Add(new JProperty(name, node.Value));
                }

                var multiresults = target.Elements()
                                    .GroupBy(e => e.Name.LocalName)
                                    .Where(e => e.Count() > 1)
                                    .SelectMany(e => e);

                string prevName = string.Empty;
                JArray jarr = null;

                foreach (var xe in multiresults)
                {
                    if (!xe.Name.LocalName.Equals(prevName))
                    {
                        if (jarr != null && !string.IsNullOrWhiteSpace(prevName))
                        {
                            jobj.Add(new JProperty(prevName, jarr));
                        }

                        jarr = new JArray();
                    }

                    if (jarr != null)
                    {
                        jarr.Add(xe.ToJContainer());
                    }

                    prevName = xe.Name.LocalName;
                }

                if (jarr != null && !string.IsNullOrWhiteSpace(prevName))
                {
                    jobj.Add(new JProperty(prevName, jarr));
                }

                var distinctresults = target.Elements()
                                        .GroupBy(e => e.Name.LocalName)
                                        .Where(e => e.Count() == 1)
                                        .SelectMany(e => e);

                foreach (var xe in distinctresults)
                {
                    jobj.Add(new JProperty(xe.Name.LocalName, xe.ToJContainer()));
                }

                return jobj;
            }

            return null;
        }
    public void GenericCollectionCopyToInsufficientArrayCapacity()
    {
      JObject o = new JObject();
      o.Add("PropertyNameValue", new JValue(1));
      o.Add("PropertyNameValue2", new JValue(2));
      o.Add("PropertyNameValue3", new JValue(3));

      ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[3], 1);
    }
        public void CreateChangedDocument(JObject oldObject, JObject newObject, ref JObject changedObject, bool handleInnerObjects = false)
        {
            foreach (var n in newObject)
            {
                if (!handleInnerObjects && (n.Key == "_id" || n.Key == "_key" || n.Key == "_rev" || n.Key == "_from" || n.Key == "_to"))
                    continue;

                JToken newValue = n.Value;
                JToken oldValue = oldObject[n.Key];

                if (newValue.Type == JTokenType.Object)
                {
                    JObject subChangeObject = new JObject();

                    if (oldValue.Type == JTokenType.Null)
                        oldValue = new JObject();

                    CreateChangedDocument(oldValue as JObject, newValue as JObject, ref subChangeObject, handleInnerObjects: true);
                    if (subChangeObject.Count != 0)
                        changedObject.Add(n.Key, subChangeObject);
                }
                else if (newValue == null || !JObject.DeepEquals(oldValue, newValue))
                {
                    changedObject.Add(n.Key, newValue);
                }
            }
        }
Example #60
0
        /// <summary>
        /// On GUI draw call.
        /// </summary>
        protected virtual void OnGUI()
        {
            // Label style
            labelFormat           = new GUIStyle();
            labelFormat.alignment = TextAnchor.MiddleCenter;
            labelFormat.fontSize  = 12;

            // Label error style
            errorFormat = new GUIStyle(labelFormat);
            errorFormat.normal.textColor = Color.red;

            // Input style
            inputFormat             = new GUIStyle(GUI.skin.textField);
            inputFormat.alignment   = TextAnchor.LowerCenter;
            inputFormat.fontSize    = 12;
            inputFormat.fixedHeight = 20;

            // Button style
            buttonFormat            = new GUIStyle(GUI.skin.button);
            buttonFormat.alignment  = TextAnchor.MiddleCenter;
            buttonFormat.fixedWidth = 100;


            // Name
            GUILayout.Space(10f);
            EditorGUILayout.LabelField("Enter a name for this controller:", labelFormat);
            GUILayout.Space(10f);

            // Input
            tempName = EditorGUILayout.TextField(tempName, inputFormat);
            GUILayout.Space(14f);

            // Error
            EditorGUILayout.LabelField(errorString, errorFormat);
            GUILayout.Space(20f);

            // Buttons
            EditorGUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();

            // Cancel button
            if (GUILayout.Button("Cancel", buttonFormat))
            {
                NewControllerWindow.window.Close();
            }

            GUILayout.FlexibleSpace();

            // Create new controller
            if (GUILayout.Button("OK", buttonFormat))
            {
                // Check length
                if (tempName.Length >= 3)
                {
                    // Check for special chars
                    if (!namingConventions.Match(tempName).Success)
                    {
                        JObject controller = new JObject();
                        controller.Add("name", tempName);
                        controller.Add("views", new JObject());

                        FileManager.WriteJSON(controller, String.Format("{0:G}{1:G}/data/controller/{2:G}.json", Application.dataPath, Config.WebServerPath, tempName));

                        // Fire controller created event
                        if (ControllerCreated != null)
                        {
                            ControllerCreated(tempName);
                        }

                        NewControllerWindow.window.Close();
                    }
                    else
                    {
                        errorString = "The controller name must not have any special characters\nwith the exception of '-' and '_'.";
                    }
                }
                else
                {
                    errorString = "The controller name must be at least three characters long.";
                }
            }

            GUILayout.FlexibleSpace();
            EditorGUILayout.EndHorizontal();
        }