public void RetrievingACustomerAddressByType(JArray addresses)
        {
            const int CustomerId = 346760;

            "Given existing addresses".
                 f(() =>
                 {
                     MockAddressesStore.Setup(i => i.GetCustomerAddresses(It.Is<int>(customerId => customerId == CustomerId), It.Is<AddressesFilter>(addressFilter => addressFilter.Type.Contains(this.AddressTypes[1])))).Returns((int customerId, AddressesFilter addressFilter) =>
                     {
                         var filteredAddresses = from n in this.FakeAddresses
                                                 where n.Value<int>("OwnerId") == customerId &&
                                                       addressFilter.Type.Contains(n.Value<string>("Type"))
                                                 select n;

                         return Task.FromResult<dynamic>(filteredAddresses);
                     });
                 });
            "When a GET 'address type for a customer' request is sent".
                f(() =>
                {
                    Response = Client.GetAsync(new Uri(string.Format(_customerAddressesFormat, CustomerId) + "?Type=" + this.AddressTypes[1])).Result;
                });
            "Then the request is received by the API Controller".
                f(() => MockAddressesStore.Verify(i => i.GetCustomerAddresses(It.Is<int>(customerId => customerId == CustomerId), It.Is<AddressesFilter>(addressFilter => addressFilter.Type.Contains(this.AddressTypes[1])))));
            "Then a response is received by the HTTP client".
                f(() =>
                {
                    Response.Content.ShouldNotBeNull();
                });
            "Then content should be returned".
                f(() =>
                {
                    addresses = Response.Content.ReadAsAsync<JArray>().Result;
                    addresses.ShouldNotBeNull();
                });
            "Then a '200 OK' status is returned".
                f(() => Response.StatusCode.ShouldEqual(HttpStatusCode.OK));
            "Then an address is returned".
                f(() => addresses.Count().ShouldEqual(1));
            "Then each address references the queried customer".
                f(() => addresses.ToList().ForEach(address => CustomerId.ShouldEqual(address.Value<int>("OwnerId"))));
            "Then each address references the queried type".
                f(() => addresses.ToList().ForEach(address => address.Value<string>("Type").ShouldEqual(this.AddressTypes[1])));
        }
        public void RetrievingAllAddressesForOwnerIds(JArray addresses)
        {
            const int OwnerId1 = 346760;
            const int OwnerId2 = 42165;

            "Given existing addresses".
                 f(() =>
                 {
                     MockAddressesStore.Setup(i => i.GetAddresses(It.Is<AddressesFilter>(addressFilter => addressFilter.OwnerId.Contains(OwnerId1) && addressFilter.OwnerId.Contains(OwnerId2)))).Returns((AddressesFilter addressFilter) =>
                     {
                         var filteredAddresses = from n in this.FakeAddresses
                                                 where addressFilter.OwnerId.Contains(n.Value<int>("OwnerId"))
                                                 select n;

                         return Task.FromResult<dynamic>(filteredAddresses);
                     });
                 });
            "When a GET 'addresses for multiple owner ids' request is sent".
                f(() =>
                {
                    Response = Client.GetAsync(new Uri(_addressesUri + "/?OwnerId=" + OwnerId1 + "&OwnerId=" + OwnerId2)).Result;
                });
            "Then the request is received by the API Controller".
                  f(() => MockAddressesStore.Verify(i => i.GetAddresses(It.Is<AddressesFilter>(addressFilter => addressFilter.OwnerId.Contains(OwnerId1) && addressFilter.OwnerId.Contains(OwnerId2)))));
            "Then a response is received by the HTTP client".
                f(() =>
                {
                    Response.Content.ShouldNotBeNull();
                });
            "Then content should be returned".
                f(() =>
                {
                    addresses = Response.Content.ReadAsAsync<JArray>().Result;
                    addresses.ShouldNotBeNull();
                });
            "Then a '200 OK' status is returned".
                f(() => Response.StatusCode.ShouldEqual(HttpStatusCode.OK));
            "Then the expected addresses are returned".
                f(() => addresses.Count().ShouldEqual(4));
            "Then each address references a queried owner".
                f(() => addresses.ToList().ForEach(address => new int[] { OwnerId1, OwnerId2 }.ShouldContain(address.Value<int>("OwnerId"))));
        }
Beispiel #3
0
        public void AddFirst()
        {
            JArray a =
            new JArray(
              5,
              new JArray(1),
              new JArray(1, 2),
              new JArray(1, 2, 3)
            );

              a.AddFirst("First");

              Assert.AreEqual("First", (string)a[0]);
              Assert.AreEqual(a, a[0].Parent);
              Assert.AreEqual(a[1], a[0].Next);
              Assert.AreEqual(5, a.Count());

              a.AddFirst("NewFirst");
              Assert.AreEqual("NewFirst", (string)a[0]);
              Assert.AreEqual(a, a[0].Parent);
              Assert.AreEqual(a[1], a[0].Next);
              Assert.AreEqual(6, a.Count());

              Assert.AreEqual(a[0], a[0].Next.Previous);
        }
        public String GetEducationOrganizationId(JArray Links)
        {
            try
            {
                string educationOrganization = "";
                for (int index = 0; index < Links.Count(); index++)
                {
                    String relation = _authenticateUser.GetStringWithoutQuote(Links["rel"].ToString());
                    if (relation.Equals("getEducationOrganizations"))
                    {
                        String result = RestApiHelper.CallApiWithParameter(_authenticateUser.GetStringWithoutQuote(Links[index]["href"].ToString()), this._accessToken);
                        JArray educationOrganizationResponse = JArray.Parse(result);

                        for (int i = 0; i < educationOrganizationResponse.Count(); i++)
                        {
                            JToken token = educationOrganizationResponse[i];
                            educationOrganization = _authenticateUser.GetStringWithoutQuote(token["id"].ToString());
                            string organizationCategories = token["organizationCategories"].ToString();

                            if (organizationCategories.Contains("State Education Agency"))
                                educationOrganization = "State Education Agency";

                            break;
                        }
                        return educationOrganization;
                    }
                }
                return educationOrganization;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        public void RetrievingAddressesByCity(JArray addresses)
        {
            const string City = "Denver";

            "Given existing addresses".
                 f(() =>
                 {
                     MockAddressesStore.Setup(i => i.GetAddresses(It.Is<AddressesFilter>(addressFilter => addressFilter.City == City))).Returns((AddressesFilter addressFilter) =>
                     {
                         var filteredAddresses = from n in this.FakeAddresses
                                                 where n.Value<string>("City").ToLowerInvariant().Contains(City.ToLowerInvariant())
                                                 select n;

                         return Task.FromResult<dynamic>(filteredAddresses);
                     });
                 });
            "When a GET 'addresses by city' request is sent".
                  f(() =>
                  {
                      Response = Client.GetAsync(_addressesUri + "/?City=" + City).Result;
                  });
            "Then the request is received by the API Controller".
                f(() => MockAddressesStore.Verify(i => i.GetAddresses(It.Is<AddressesFilter>(addressFilter => addressFilter.City == City))));
            "Then a response is received by the HTTP client".
                f(() =>
                {
                    Response.Content.ShouldNotBeNull();
                });
            "Then content should be returned".
                f(() =>
                {
                    addresses = Response.Content.ReadAsAsync<JArray>().Result;
                    addresses.ShouldNotBeNull();
                });
            "Then a '200 OK' status is returned".
                f(() => Response.StatusCode.ShouldEqual(HttpStatusCode.OK));
            "Then addresses are returned".
                f(() => addresses.Count().ShouldEqual(3));
            "Then each address's city references the queried city".
                f(() => addresses.ToList().ForEach(address => address.Value<string>("City").ToLowerInvariant().ShouldContain(City.ToLowerInvariant())));
        }
        public Dictionary <string, string> GetValueFromWebService(JArray jsonObject, string NameReport, List <string> ValuesLog)
        {
            Dictionary <string, string> DicValuesFilterColumn = new Dictionary <string, string>();
            Singleton PatronSingleton = Singleton.Instance;

            try
            {
                //Al final el dictionario debe quedar así, EMPRESA es el valor FiltroColumna de la Tabla FiltroReporte,
                //y el valor ó dato de ese FiltroColumna.  Casualmente el nombre del FiltroTabla es Empresa, pero difiere
                //en cuanto mayúsculas. Cuando el campo FiltroColumna, tenga varios valores, se dividirá con el símbolo -
                var NameFiltro = jsonObject[0]["NOMBREFILTRO"];
                var DatoFiltro = jsonObject[0]["DATOFILTRO"];


                string Item = String.Empty;

                Dictionary <string, string> DicNameFiltro = new Dictionary <string, string>();
                Dictionary <string, string> DicDatoFiltro = new Dictionary <string, string>();
                List <string> LstNameFiltro       = new List <string>();
                List <string> LstNameFiltroDupli  = new List <string>();
                List <string> LstValueFiltro      = new List <string>();
                List <string> LstValueFiltroDupli = new List <string>();
                Newtonsoft.Json.Linq.JArray jsonObjectDetalles = null;

                List <List <string> > LstLstDatoFiltro = new List <List <string> >();

                foreach (var valor in NameFiltro)
                {
                    string NameFilter = (string)valor["NOMBREFILTRO"];
                    LstNameFiltro.Add(NameFilter);
                    LstNameFiltroDupli.Add(NameFilter);
                }

                foreach (var valor in DatoFiltro)
                {
                    string NameFilter = (string)valor["datoFil"];
                    LstValueFiltro.Add(NameFilter);
                    LstValueFiltroDupli.Add(NameFilter);
                }

                //Guardo en una Lista los datos, por cada Filtro.
                //Aquí debo hacer un math con el campo WebServiceConnect,
                //Sí DATOFILTRO, no tiene campos de descripción, sino solo datos, se tomara ese dato.
                //Busco por medio del Nombre del Reporte, los valores que tiene el campo WebServiceConnect
                //Para hacer Math con el campo WebServiceConnect
                List <Models.Filter> ValuesFieldConnect = GetValueFieldConnect(NameReport);


                int                  i              = 0;
                Models.Filter        ItemFilter     = new  Models.Filter();
                List <Models.Filter> Items          = new List <Models.Filter>();
                int                  cantidadFiltro = LstNameFiltro.Count();
                int                  m              = 0;

                for (int l = 0; l < cantidadFiltro; l++)
                {
                    string  NameFilter = LstNameFiltroDupli[l];
                    string  DatoFilter = LstValueFiltroDupli[l];
                    dynamic Resultado  = ValuesFieldConnect.Where(p => p.NombreFiltro == NameFilter).FirstOrDefault();
                    ItemFilter = ValuesFieldConnect.Where(p => p.NombreFiltro == NameFilter).FirstOrDefault();
                    if (ItemFilter != null)
                    {
                        Items.Add(ItemFilter);
                    }
                    else
                    {
                        //Guarda Log
                        ValuesLog.Add("Configuración de Filtros: Filtro Ausente: " + NameFilter);
                        ValuesLog.Add("INFO");
                        PatronSingleton.AddValuesTableLog(ValuesLog);

                        LstNameFiltro.Remove(NameFilter);
                        LstValueFiltro.RemoveAt(m);
                        DatoFiltro[m].Remove();
                        m--;
                    }
                    m++;
                }



                foreach (var detallesField in Items)
                {
                    List <string> LstDatoFiltro = new List <string>();
                    Item = detallesField.WebServiceConnect;
                    for (int j = 0; j < DatoFiltro.Count(); j++)
                    {
                        dynamic DetallesRegistros = DatoFiltro[j];
                        var     itemValorDetalle  = String.Empty;
                        string  DataFilter1       = (string)DetallesRegistros["datoFil"];


                        jsonObjectDetalles = JArray.Parse(DataFilter1);
                        if (jsonObjectDetalles.Count() == 1)
                        {
                            string valoresFiltro = DetallesRegistros.GetValue("datoFil");
                            itemValorDetalle = (string)jsonObjectDetalles[0][Item];
                            if (itemValorDetalle != null)
                            {
                                LstDatoFiltro.Add(itemValorDetalle);
                                string cadenaAplanada = String.Join("-", LstDatoFiltro);
                                LstDatoFiltro = new List <string>();
                                LstDatoFiltro.Add(cadenaAplanada);
                                LstLstDatoFiltro.Add(LstDatoFiltro);
                                break;
                            }
                        }
                        else
                        {
                            for (int k = 0; k < jsonObjectDetalles.Count(); k++)
                            {
                                itemValorDetalle = (string)jsonObjectDetalles[k][Item];
                                if (itemValorDetalle != null)
                                {
                                    LstDatoFiltro.Add(itemValorDetalle);
                                    string cadenaAplanada = String.Join("-", LstDatoFiltro);
                                    LstDatoFiltro = new List <string>();
                                    LstDatoFiltro.Add(cadenaAplanada);
                                }
                                else
                                {
                                    break;
                                }
                            }
                            if (LstDatoFiltro.Count > 0)
                            {
                                LstLstDatoFiltro.Add(LstDatoFiltro);
                                LstDatoFiltro = new List <string>();
                            }
                        }
                    }
                }

                //Este for, es para dividir la lista,
                //si tiene mas de un valor, este se separa con el símbolo del guión medio

                for (int j = 0; j < LstNameFiltro.Count(); j++)
                {
                    DicValuesFilterColumn.Add(LstNameFiltro[j].ToString(), LstLstDatoFiltro[j][0].ToString());
                }


                //DicValuesFilterColumn.Add("EMPRESA", "01");
                //DicValuesFilterColumn.Add("BAJO", "0,05-0,06");
                //DicValuesFilterColumn.Add("FECHA_APERTURA", "2019/11/30");
                return(DicValuesFilterColumn);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Beispiel #7
0
            /// <summary>
            /// Initializes a new instance of the <see cref="Position"/> class.
            /// </summary>
            /// <param name="array">
            /// The <see cref="JToken"/> holding 2 or three doubles.
            /// </param>
            /// <exception cref="ArgumentException">
            /// If <paramref name="array"/> holds less than 2 values.
            /// </exception>
            public Position(JArray array)
            {
                if (array.Count() < 2)
                {
                    throw new ArgumentException(
                    string.Format("Expected at least 2 elements, got {0}", array.Count()),
                    "array");
                }

                this.P1 = (double)array[0];
                this.P2 = (double)array[1];
                if (array.Count() > 2)
                {
                    this.P3 = (double)array[2];
                    if (array.Count() > 3)
                    {
                        this.P4 = (double)array[3];
                    }
                }
            }
        public void RetrievingAddressesByStreet2(JArray addresses)
        {
            const string Street2 = "VOGELWEIHERSTR";

            "Given existing addresses".
                 f(() =>
                 {
                     MockAddressesStore.Setup(i => i.GetAddresses(It.Is<AddressesFilter>(addressFilter => addressFilter.Street2.Contains(Street2)))).Returns((AddressesFilter addressFilter) =>
                     {
                         var filteredAddresses = from n in this.FakeAddresses
                                                 where n.Value<string>("Street2") != null &&
                                                       n.Value<string>("Street2").Contains(addressFilter.Street2)
                                                 select n;

                         return Task.FromResult<dynamic>(filteredAddresses);
                     });
                 });
            "When a GET 'addresses by street2' request is sent".
                f(() =>
                {
                    Response = Client.GetAsync(_addressesUri + "/?Street2=" + Street2).Result;
                });
            "Then the request is received by the API Controller".
                f(() => MockAddressesStore.Verify(i => i.GetAddresses(It.Is<AddressesFilter>(addressFilter => addressFilter.Street2.Contains(Street2)))));
            "Then a response is received by the HTTP client".
                f(() =>
                {
                    Response.Content.ShouldNotBeNull();
                });
            "Then content should be returned".
                f(() =>
                {
                    addresses = Response.Content.ReadAsAsync<JArray>().Result;
                    addresses.ShouldNotBeNull();
                });
            "Then a '200 OK' status is returned".
                f(() => Response.StatusCode.ShouldEqual(HttpStatusCode.OK));
            "Then addresses are returned".
                f(() => addresses.Count().ShouldEqual(1));
            "Then each address references the queried street2".
                f(() => addresses.ToList().ForEach(address => address.Value<string>("Street2").ShouldContain(Street2)));
        }
        public void CreateWriter()
        {
            JArray a =
                new JArray(
                    5,
                    new JArray(1),
                    new JArray(1, 2),
                    new JArray(1, 2, 3)
                    );

            JsonWriter writer = a.CreateWriter();
            Assert.IsNotNull(writer);
            Assert.AreEqual(4, a.Count());

            writer.WriteValue("String");
            Assert.AreEqual(5, a.Count());
            Assert.AreEqual("String", (string)a[4]);

            writer.WriteStartObject();
            writer.WritePropertyName("Property");
            writer.WriteValue("PropertyValue");
            writer.WriteEnd();

            Assert.AreEqual(6, a.Count());
            Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("Property", "PropertyValue")), a[5]));
        }
        public void Children()
        {
            JArray a =
                new JArray(
                    5,
                    new JArray(1),
                    new JArray(1, 2),
                    new JArray(1, 2, 3)
                    );

            Assert.AreEqual(4, a.Count());
            Assert.AreEqual(3, a.Children<JArray>().Count());
        }
        public void AddAfterSelf()
        {
            JArray a =
                new JArray(
                    5,
                    new JArray(1),
                    new JArray(1, 2),
                    new JArray(1, 2, 3)
                    );

            a[1].AddAfterSelf("pie");

            Assert.AreEqual(5, (int)a[0]);
            Assert.AreEqual(1, a[1].Count());
            Assert.AreEqual("pie", (string)a[2]);
            Assert.AreEqual(5, a.Count());

            a[4].AddAfterSelf("lastpie");

            Assert.AreEqual("lastpie", (string)a[5]);
            Assert.AreEqual("lastpie", (string)a.Last);
        }
        public int UpdateInterruptionInfo(JArray info, string interruptionInfoFilePath,string currentInterruptionsInfoFilePath)
        {
            var parentJson = new JArray();
            foreach (var interruption in info) //Converting one by one so that if any one location fails, others are not affected
            {
                var location = interruption.Value<string>("Name");
                try
                {
                    var interruptionJsonString = JsonConvert.SerializeObject(interruption);
                    var interruptionJsonObj = JObject.Parse(interruptionJsonString);
                    parentJson.Add(interruptionJsonObj);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error converting location {0}", location);
                    Console.WriteLine(ex.Message);
                }

            }
            var fullIntteruptionInfo = JsonConvert.SerializeObject(parentJson, Formatting.Indented);
            File.WriteAllText(interruptionInfoFilePath, fullIntteruptionInfo);
            
            UpdateCurrentInterruptionInfo(interruptionInfoFilePath,currentInterruptionsInfoFilePath);

            return info.Count();

        }
        public void RetrievingAllAddressesForOwnerTypes(JArray addresses)
        {
            string[] ownerType = { "BUS", "PER" };

            "Given existing addresses".
                 f(() =>
                 {
                     MockAddressesStore.Setup(i => i.GetAddresses(It.Is<AddressesFilter>(addressFilter => addressFilter.OwnerType.Contains(ownerType[0]) && addressFilter.OwnerType.Contains(ownerType[1])))).Returns((AddressesFilter addressFilter) =>
                     {
                         var filteredAddresses = from n in this.FakeAddresses
                                                 where addressFilter.OwnerType.Contains(n.Value<string>("OwnerType"))
                                                 select n;

                         return Task.FromResult<dynamic>(filteredAddresses);
                     });
                 });
            "When a GET 'addresses for multiple owner types' request is sent".
                f(() =>
                {
                    Response = Client.GetAsync(new Uri(_addressesUri + "/?OwnerType=" + ownerType[0] + "&OwnerType=" + ownerType[1])).Result;
                });
            "Then the request is received by the API Controller".
                  f(() => MockAddressesStore.Verify(i => i.GetAddresses(It.Is<AddressesFilter>(addressFilter => addressFilter.OwnerType.Contains(ownerType[0]) && addressFilter.OwnerType.Contains(ownerType[1])))));
            "Then a response is received by the HTTP client".
                f(() =>
                {
                    Response.Content.ShouldNotBeNull();
                });
            "Then content should be returned".
                f(() =>
                {
                    addresses = Response.Content.ReadAsAsync<JArray>().Result;
                    addresses.ShouldNotBeNull();
                });
            "Then a '200 OK' status is returned".
                f(() => Response.StatusCode.ShouldEqual(HttpStatusCode.OK));
            "Then the expected addresses are returned".
                f(() => addresses.Count().ShouldEqual(9));
            "Then each address references a queried owner type".
                f(() => addresses.ToList().ForEach(address => new string[] { ownerType[0], ownerType[1] }.ShouldContain(address.Value<string>("OwnerType"))));
        }
        public void RetrievingAllAddressesForOwnerName(JArray addresses)
        {
            const string OwnerNameTest = "THE DILLION COMPANY";

            "Given existing addresses".
                 f(() =>
                 {
                     MockAddressesStore.Setup(i => i.GetAddresses(It.Is<AddressesFilter>(addressFilter => addressFilter.OwnerName.Contains(OwnerNameTest)))).Returns((AddressesFilter addressFilter) =>
                     {
                         var filteredAddresses = from n in this.FakeAddresses
                                                 where addressFilter.OwnerName.Contains(n.Value<string>("OwnerName"))
                                                 select n;

                         return Task.FromResult<dynamic>(filteredAddresses);
                     });
                 });
            "When a GET 'all addresses for owner name' request is sent".
                f(() =>
                {
                    Response = Client.GetAsync(new Uri(_addressesUri + "/?OwnerName=" + OwnerNameTest)).Result;
                });
            "Then the request is received by the API Controller".
                f(() => MockAddressesStore.Verify(i => i.GetAddresses(It.Is<AddressesFilter>(addressFilter => addressFilter.OwnerName.Contains(OwnerNameTest)))));
            "Then a response is received by the HTTP client".
                f(() =>
                {
                    Response.Content.ShouldNotBeNull();
                });
            "Then content should be returned".
                f(() =>
                {
                    addresses = Response.Content.ReadAsAsync<JArray>().Result;
                    addresses.ShouldNotBeNull();
                });
            "Then a '200 OK' status is returned".
                f(() => Response.StatusCode.ShouldEqual(HttpStatusCode.OK));
            "Then all addresses are returned for the queried owner name".
                f(() => addresses.Count().ShouldEqual(3));
            "Then each address references the expected owner name".
                f(() => addresses.ToList().ForEach(address => address.Value<string>("OwnerName").ShouldEqual(OwnerNameTest)));
        }
        public String GetCustomLink(JArray Links)
        {
            try
            {
                //JObject HomeUrlResponse = JObject.Parse(RestApiHelper.CallApi("home", this._accessToken));
                //JArray Links = (JArray)HomeUrlResponse["links"];
                String CustomLink = "";
                for (int Index = 0; Index < Links.Count(); Index++)
                {
                    String Relation = _authenticateUser.GetStringWithoutQuote(Links[Index]["rel"].ToString());
                    if (Relation.Equals("custom"))
                        CustomLink = _authenticateUser.GetStringWithoutQuote(Links[Index]["href"].ToString());

                }
                return CustomLink;
            }
            catch (Exception Ex)
            {
                return null;
            }
        }
 public void RetrievingAllAddresses(JArray addresses)
 {
     "Given existing addresses".
          f(() =>
          {
              MockAddressesStore.Setup(i => i.GetAddresses(It.Is<AddressesFilter>(filter => filter == null))).Returns<dynamic>(filter =>
              {
                  return Task.FromResult<dynamic>(this.FakeAddresses);
              });
          });
     "When a GET addresses request is sent".
         f(() =>
         {
             Response = Client.GetAsync(_addressesUri).Result;
         });
     "Then the request is received by the API Controller".
         f(() => MockAddressesStore.Verify(i => i.GetAddresses(It.IsAny<AddressesFilter>())));
     "Then a response is received by the HTTP client".
         f(() =>
         {
             Response.Content.ShouldNotBeNull();
         });
     "Then content should be returned".
         f(() =>
         {
             addresses = Response.Content.ReadAsAsync<JArray>().Result;
             addresses.ShouldNotBeNull();
         });
     "Then a '200 OK' status is returned".
         f(() => Response.StatusCode.ShouldEqual(HttpStatusCode.OK));
     "Then all addresses are returned for all customers".
         f(() => addresses.Count().ShouldEqual(this.FakeAddresses.Count()));
 }
        public void RetrievingAddressesByTypes(JArray addresses)
        {
            "Given existing addresses".
                 f(() =>
                 {
                     MockAddressesStore.Setup(i => i.GetAddresses(It.Is<AddressesFilter>(addressFilter => addressFilter.Type.Contains(this.AddressTypes[0]) && addressFilter.Type.Contains(this.AddressTypes[1])))).Returns((AddressesFilter addressFilter) =>
                     {
                         var filteredAddresses = from n in this.FakeAddresses
                                                 where addressFilter.Type.Contains(n.Value<string>("Type"))
                                                 select n;

                         return Task.FromResult<dynamic>(filteredAddresses);
                     });
                 });
            "When a GET 'addresses by multiple types' request is sent".
                f(() =>
                {
                    Response = Client.GetAsync(_addressesUri + "/?Type=" + this.AddressTypes[0] + "&Type=" + this.AddressTypes[1]).Result;
                });
            "Then the request is received by the API Controller".
                f(() => MockAddressesStore.Verify(i => i.GetAddresses(It.Is<AddressesFilter>(addressFilter => addressFilter.Type.Contains(this.AddressTypes[1]) && addressFilter.Type.Contains(this.AddressTypes[1])))));
            "Then a response is received by the HTTP client".
                f(() =>
                {
                    Response.Content.ShouldNotBeNull();
                });
            "Then content should be returned".
                f(() =>
                {
                    addresses = Response.Content.ReadAsAsync<JArray>().Result;
                    addresses.ShouldNotBeNull();
                });
            "Then a '200 OK' status is returned".
                f(() => Response.StatusCode.ShouldEqual(HttpStatusCode.OK));
            "Then addresses are returned".
                f(() => addresses.Count().ShouldEqual(6));
            "Then each address references a queried type".
                f(() => addresses.ToList().ForEach(address => new string[] { this.AddressTypes[0], this.AddressTypes[1] }.Contains(address.Value<string>("Type"))));
        }
Beispiel #18
0
        public void GetSubcomments(JArray x)
        {
         
            for (int i = 0; i < x.Count(); i++)
            {

                var asd = new SingleImageComments(
                    (string)x[i]["id"],
                    (string)x[i]["comment"],
                    (string)x[i]["author"] + " :",
                    UnixToDateTime((string)x[i]["datetime"]),(JArray)x[i]["children"]
                     );

              comments.Add(asd);
/*
              if (x[i]["children"].Count() > 0)
                {

                    JArray y = (JArray)x[i]["children"];
                    GetSubcomments(y);
               }
 */
             

            }
        }
        public void RetrievingAnAddressTypeForAnOwner(JArray addresses)
        {
            const int OwnerIdTest = 346760;

            "Given existing addresses".
                 f(() =>
                 {
                     MockAddressesStore.Setup(i => i.GetAddresses(It.Is<AddressesFilter>(addressFilter => addressFilter.OwnerId.Contains(OwnerIdTest) && addressFilter.Type.Contains(this.AddressTypes[2])))).Returns((AddressesFilter addressFilter) =>
                     {
                         var filteredAddresses = from n in this.FakeAddresses
                                                 where addressFilter.OwnerId.Contains(n.Value<int>("OwnerId")) &&
                                                       addressFilter.Type.Contains(n.Value<string>("Type"))
                                                 select n;

                         return Task.FromResult<dynamic>(filteredAddresses);
                     });
                 });
            "When a GET 'address for owner id and type' request is sent".
                f(() =>
                {
                    Response = Client.GetAsync(new Uri(_addressesUri + "/?OwnerId=" + OwnerIdTest + "&Type=" + this.AddressTypes[2])).Result;
                });
            "Then the request is received by the API Controller".
                  f(() => MockAddressesStore.Verify(i => i.GetAddresses(It.Is<AddressesFilter>(addressFilter => addressFilter.OwnerId.Contains(OwnerIdTest) && addressFilter.Type.Contains(this.AddressTypes[2])))));
            "Then a response is received by the HTTP client".
                f(() =>
                {
                    Response.Content.ShouldNotBeNull();
                });
            "Then content should be returned".
                f(() =>
                {
                    addresses = Response.Content.ReadAsAsync<JArray>().Result;
                    addresses.ShouldNotBeNull();
                });
            "Then a '200 OK' status is returned".
                f(() => Response.StatusCode.ShouldEqual(HttpStatusCode.OK));
            "Then an address is returned".
                f(() => addresses.Count().ShouldEqual(1));
            "Then the address references the queried owner id".
                f(() => addresses.ToList().ForEach(address => OwnerIdTest.ShouldEqual(address.Value<int>("OwnerId"))));
            "Then the address references the queried type".
                f(() => addresses.ToList().ForEach(address => address.Value<string>("Type").ShouldEqual(this.AddressTypes[2])));
        }
        public void RetrievingAllCustomerAddresses(JArray addresses)
        {
            const int CustomerId = 346760;

            "Given existing addresses".
                 f(() =>
                 {
                     MockAddressesStore.Setup(i => i.GetCustomerAddresses(It.Is<int>(customerId => customerId == CustomerId), It.IsAny<AddressesFilter>())).Returns((int customerId, AddressesFilter addressFilter) =>
                     {
                         var filteredAddresses = from n in this.FakeAddresses
                                                 where customerId == n.Value<int>("OwnerId")
                                                 select n;

                         return Task.FromResult<dynamic>(filteredAddresses);
                     });
                 });
            "When a GET 'all addresses for a customer' request is sent".
                f(() =>
                {
                    Response = Client.GetAsync(new Uri(string.Format(_customerAddressesFormat, CustomerId))).Result;
                });
            "Then the request is received by the API Controller".
                f(() => MockAddressesStore.Verify(i => i.GetCustomerAddresses(It.Is<int>(customerId => customerId == CustomerId), It.IsAny<AddressesFilter>())));
            "Then a response is received by the HTTP client".
                f(() =>
                {
                    Response.Content.ShouldNotBeNull();
                });
            "Then content should be returned".
                f(() =>
                {
                    addresses = Response.Content.ReadAsAsync<JArray>().Result;
                    addresses.ShouldNotBeNull();
                });
            "Then a '200 OK' status is returned".
                f(() => Response.StatusCode.ShouldEqual(HttpStatusCode.OK));
            "Then all addresses are returned for the owner".
                f(() => addresses.Count().ShouldEqual(3));
            "Then each address references the expected owner id".
                f(() => addresses.ToList().ForEach(address => address.Value<int>("OwnerId").ShouldEqual(CustomerId)));
        }
 public void PutCustomForStaff(JArray homeLinks, Temp tempObj)
 {
     try
     {
         for (int index = 0; index < homeLinks.Count(); index++)
         {
             String relation = _authenticateUser.GetStringWithoutQuote(homeLinks[index]["rel"].ToString());
             if (relation.Equals("custom"))
             {
                 string link = _authenticateUser.GetStringWithoutQuote(homeLinks[index]["href"].ToString());
                 string result = _slcApi.FlagObjectToJson(tempObj);
                 RestApiHelper.CallApiWithParameterForCustomPUT(link, this.AccessToken, result);
             }
         }
     }
     catch (Exception ex)
     {
     }
 }
        public void RetrievingCustomerAddressesByZipCode(JArray addresses)
        {
            const int CustomerId = 346760;
            const string ZipCode = "802";

            "Given existing addresses".
                 f(() =>
                 {
                     MockAddressesStore.Setup(i => i.GetCustomerAddresses(It.Is<int>(customerId => customerId == CustomerId), It.Is<AddressesFilter>(addressFilter => addressFilter.Zip.Contains(ZipCode)))).Returns((int customerId, AddressesFilter addressFilter) =>
                     {
                         var filteredAddresses = from n in this.FakeAddresses
                                                 where n.Value<string>("ZipCode").Contains(addressFilter.Zip) &&
                                                       n.Value<int>("OwnerId") == CustomerId
                                                 select n;

                         return Task.FromResult<dynamic>(filteredAddresses);
                     });
                 });
            "When a GET 'addresses for a customer by zip code' request is sent".
                f(() =>
                {
                    Response = Client.GetAsync(new Uri(string.Format(_customerAddressesFormat, CustomerId) + "/?Zip=" + ZipCode)).Result;
                });
            "Then the request is received by the API Controller".
                f(() => MockAddressesStore.Verify(i => i.GetCustomerAddresses(It.Is<int>(customerId => customerId == CustomerId), It.Is<AddressesFilter>(addressFilter => addressFilter.Zip.Contains(ZipCode)))));
            "Then a response is received by the HTTP client".
                f(() =>
                {
                    Response.Content.ShouldNotBeNull();
                });
            "Then content should be returned".
                f(() =>
                {
                    addresses = Response.Content.ReadAsAsync<JArray>().Result;
                    addresses.ShouldNotBeNull();
                });
            "Then a '200 OK' status is returned".
                f(() => Response.StatusCode.ShouldEqual(HttpStatusCode.OK));
            "Then addresses are returned".
                f(() => addresses.Count().ShouldEqual(2));
            "Then the address references the queried customer".
                f(() => addresses.First().Value<int>("OwnerId").ShouldEqual(CustomerId));
            "Then each address references the queried zip code".
                f(() => addresses.ToList().ForEach(address => address.Value<string>("ZipCode").ShouldContain(ZipCode)));
        }
        public void Replace()
        {
            JArray a =
                new JArray(
                    5,
                    new JArray(1),
                    new JArray(1, 2),
                    new JArray(1, 2, 3)
                    );

            a[0].Replace(new JValue(int.MaxValue));
            Assert.AreEqual(int.MaxValue, (int)a[0]);
            Assert.AreEqual(4, a.Count());

            a[1][0].Replace(new JValue("Test"));
            Assert.AreEqual("Test", (string)a[1][0]);

            a[2].Replace(new JValue(int.MaxValue));
            Assert.AreEqual(int.MaxValue, (int)a[2]);
            Assert.AreEqual(4, a.Count());

            Assert.IsTrue(JToken.DeepEquals(new JArray(int.MaxValue, new JArray("Test"), int.MaxValue, new JArray(1, 2, 3)), a));
        }
        public void AddBeforeSelf()
        {
            JArray a =
                new JArray(
                    5,
                    new JArray(1),
                    new JArray(1, 2),
                    new JArray(1, 2, 3)
                    );

            a[1].AddBeforeSelf("pie");

            Assert.AreEqual(5, (int)a[0]);
            Assert.AreEqual("pie", (string)a[1]);
            Assert.AreEqual(a, a[1].Parent);
            Assert.AreEqual(a[2], a[1].Next);
            Assert.AreEqual(5, a.Count());

            a[0].AddBeforeSelf("firstpie");

            Assert.AreEqual("firstpie", (string)a[0]);
            Assert.AreEqual(5, (int)a[1]);
            Assert.AreEqual("pie", (string)a[2]);
            Assert.AreEqual(a, a[0].Parent);
            Assert.AreEqual(a[1], a[0].Next);
            Assert.AreEqual(6, a.Count());

            a.Last.AddBeforeSelf("secondlastpie");

            Assert.AreEqual("secondlastpie", (string)a[5]);
            Assert.AreEqual(7, a.Count());
        }
Beispiel #25
0
        private Right[] getRights(JArray token)
        {
            //TODO add the rest of the rights.
            Right[] rights = new Right[token.Count()];
            int count = 0;
            foreach (JToken t in token)
            {
                switch (t.Value<String>())
                {

                    case "get_info":
                        rights[count] = Right.Get_Info;
                        count++;
                        break;
                    case "deposit":
                        rights[count] = Right.Deposit;
                        count++;
                        break;
                    case "merchant":
                        rights[count] = Right.Merchant;
                        count++;
                        break;
                    case "trade":
                        rights[count] = Right.Trade;
                        count++;
                        break;
                    case "withdraw":
                        rights[count] = Right.Withdraw;
                        count++;
                        break;
                    default:
                        rights[count] = Right.None;
                        count++;
                        break;

                }

            }
            return rights;
        }
        public void Remove()
        {
            JToken t;
            JArray a =
                new JArray(
                    5,
                    6,
                    new JArray(7, 8),
                    new JArray(9, 10)
                    );

            a[0].Remove();

            Assert.AreEqual(6, (int)a[0]);

            a[1].Remove();

            Assert.AreEqual(6, (int)a[0]);
            Assert.IsTrue(JToken.DeepEquals(new JArray(9, 10), a[1]));
            Assert.AreEqual(2, a.Count());

            t = a[1];
            t.Remove();
            Assert.AreEqual(6, (int)a[0]);
            Assert.IsNull(t.Next);
            Assert.IsNull(t.Previous);
            Assert.IsNull(t.Parent);

            t = a[0];
            t.Remove();
            Assert.AreEqual(0, a.Count());

            Assert.IsNull(t.Next);
            Assert.IsNull(t.Previous);
            Assert.IsNull(t.Parent);
        }
Beispiel #27
0
 public static int PickIndex(JArray jArray)
 {
     return (int)(jArray.Count() * (new Random()).NextDouble());
 }
        public void RemoveAll()
        {
            JArray a =
                new JArray(
                    5,
                    new JArray(1),
                    new JArray(1, 2),
                    new JArray(1, 2, 3)
                    );

            JToken first = a.First;
            Assert.AreEqual(5, (int)first);

            a.RemoveAll();
            Assert.AreEqual(0, a.Count());

            Assert.IsNull(first.Parent);
            Assert.IsNull(first.Next);
        }
        public String GetEducationOrganizationId(JArray Links)
        {
            try
            {
                //JObject HomeUrlResponse = JObject.Parse(RestApiHelper.CallApi("home", this._accessToken));
                //JArray Links = (JArray)HomeUrlResponse["links"];
                String EducationOrganization = "";
                for (int Index = 0; Index < Links.Count(); Index++)
                {
                    String Relation = _authenticateUser.GetStringWithoutQuote(Links[Index]["rel"].ToString());
                    if (Relation.Equals("getEducationOrganizations"))
                    {
                        String Result = RestApiHelper.CallApiWithParameter(_authenticateUser.GetStringWithoutQuote(Links[Index]["href"].ToString()), this._accessToken);
                        JArray EducationOrganizationResponse = JArray.Parse(Result);

                        for (int i = 0; i < EducationOrganizationResponse.Count(); i++)
                        {
                            JToken Token = EducationOrganizationResponse[i];
                            EducationOrganization = _authenticateUser.GetStringWithoutQuote(Token["id"].ToString());
                            String OrganizationCategories = Token["organizationCategories"].ToString();
                            if (OrganizationCategories.Contains("State Education Agency"))
                                EducationOrganization = "State Education Agency";

                            break;
                        }
                        return EducationOrganization;
                    }
                }
                return EducationOrganization;
            }
            catch (Exception Ex)
            {
                return null;
            }
        }
    public void CreateJTokenTree()
    {
      JObject o =
        new JObject(
          new JProperty("Test1", "Test1Value"),
          new JProperty("Test2", "Test2Value"),
          new JProperty("Test3", "Test3Value"),
          new JProperty("Test4", null)
        );

      Assert.AreEqual(4, o.Properties().Count());

      Assert.AreEqual(@"{
  ""Test1"": ""Test1Value"",
  ""Test2"": ""Test2Value"",
  ""Test3"": ""Test3Value"",
  ""Test4"": null
}", o.ToString());

      JArray a =
        new JArray(
          o,
          new DateTime(2000, 10, 10, 0, 0, 0, DateTimeKind.Utc),
          55,
          new JArray(
            "1",
            2,
            3.0,
            new DateTime(4, 5, 6, 7, 8, 9, DateTimeKind.Utc)
          ),
          new JConstructor(
            "ConstructorName",
            "param1",
            2,
            3.0
          )
        );

      Assert.AreEqual(5, a.Count());
      Assert.AreEqual(@"[
  {
    ""Test1"": ""Test1Value"",
    ""Test2"": ""Test2Value"",
    ""Test3"": ""Test3Value"",
    ""Test4"": null
  },
  ""2000-10-10T00:00:00Z"",
  55,
  [
    ""1"",
    2,
    3.0,
    ""0004-05-06T07:08:09Z""
  ],
  new ConstructorName(
    ""param1"",
    2,
    3.0
  )
]", a.ToString());
    }
	/// <summary>
	/// <para>Given a list of high scores, returns the best high scores for ghost mode. 
	/// Preference in order:</para>
	/// <para>- First, Ghosts with similar scores</para>
	/// <para>- Then, sort by connected players, friends, city, region, country, world</para>
	/// <para>If multiple Ghosts have the same preference score, random ones are chosen</para>
	/// </summary>
	/// <param name="highscores">Highscores.</param>
	/// <param name="count">How many ghosts you would like to get.</param>
	/// <param name="count">Optimal minimum score factor a ghost needs to have compared to the best score of a connected player. Default is 0.75f.</param>
	/// <param name="count">Optimal maximum score factor a ghost needs to have compared to the best score of a connected player. Default is 1.5f.</param>
	/// <returns>List of highscore entries that are best suited for ghost mode.</returns>
	public static JToken SelectBestGhosts(JToken highscores, int count, float minScoreFactor = 0.75f, float maxScoreFactor = 1.5f){
		float myScore = -1;
		List<JToken> candidates = new List<JToken>();

		for (int i = 0; i < highscores.Count(); ++i) {
			JObject highscore = (JObject)highscores [i];
			if (highscore["relationship"].ToString() == "requested"){
				if (myScore == -1 || myScore < (float)highscore["score"]) { 
					myScore = (float)highscore["score"];
				}
			}
			candidates.Add (highscore);
		}

		JObject preference = new JObject ();
		preference.Add("world", 1);
		preference.Add("country", 2);
		preference.Add("region", 3);
		preference.Add("city", 4);
		preference.Add("friends", 5);
		preference.Add("similar_score", 10);
		preference.Add("requested", 20);

		int randomUID = Mathf.FloorToInt(Random.value * 65536);
		int randomUIDChar = Mathf.FloorToInt(Random.value * 32);

		JArray result = new JArray ();
		foreach (JToken candidate in candidates.OrderBy (element => SortScore (element, preference, myScore, minScoreFactor, maxScoreFactor, randomUID, randomUIDChar))) {
			result.Add(candidate);
			if (result.Count() == count){
				break;
			}
		} 

		return result;

	}