Esempio n. 1
0
        public async Task GetUserById_ExistingUser_Ok()
        {
            // Arrange
            var adminToRequest = MockApplicationUsers.Get(0);
            var userToFind     = MockApplicationUsers.Get(1);
            var expectedDto    = new ApplicationUserDto(userToFind);
            var path           = $"{Routes.UserRoute}/{userToFind.Id}";
            var token          = await GetToken(adminToRequest);

            _endSystems.SetBearerToken(token);

            // Act
            var response = await _endSystems.Get(path);

            var dto = JsonStringSerializer.GetApplicationUserDto(response.Body);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.Code);
            Assert.Equal(expectedDto.Id, dto.Id);
            Assert.Equal(expectedDto.Email, dto.Email);
            Assert.Equal(expectedDto.Name, dto.Name);

            // Tear down
            _endSystems.Dispose();
        }
Esempio n. 2
0
        public async Task GetAllTodos_UserHasTokenNoQuery_OkAndDtoArray()
        {
            // Arrange
            var user  = MockApplicationUsers.Get(4);
            var todos = MockTodos
                        .GetAll()
                        .Where(w => w.Owner.Id == user.Id)
                        .OrderBy(w => w.Due)
                        .ToArray();
            var path  = Routes.TodoRoute;
            var token = await GetToken(user);

            _endSystems.SetBearerToken(token);

            // Act
            var response = await _endSystems.Get(path);

            var dtos = JsonStringSerializer.GetListOfTodoto(response.Body);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.Code);
            CheckOrderAndEqual(todos, dtos);

            // Tear down
            _endSystems.Dispose();
        }
Esempio n. 3
0
        public async Task GetTodo_UserOwnsTodoAndBothExist_OkWithDto()
        {
            // Arrange
            var todo = MockTodos.Get(14);
            var user = MockApplicationUsers
                       .GetAll()
                       .SingleOrDefault(w => w.Id == todo.Owner.Id);
            var path  = $"{Routes.TodoRoute}/{todo.Id}";
            var token = await GetToken(user);

            _endSystems.SetBearerToken(token);

            // Act
            var response = await _endSystems.Get(path);

            var dto = JsonStringSerializer.GetTodoDto(response.Body);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.Code);
            Assert.Equal(todo.Id, dto.Id);
            Assert.Equal(todo.Description, dto.Description);
            Assert.Equal(todo.Due, dto.Due);

            // Tear down
            _endSystems.Dispose();
        }
Esempio n. 4
0
        private void LoadAlarms(string alarmsFilePath)
        {
            if (!File.Exists(alarmsFilePath))
            {
                _logger.Error($"Failed to load file alarms file '{alarmsFilePath}'...");
                return;
            }

            var alarmData = File.ReadAllText(alarmsFilePath);

            if (string.IsNullOrEmpty(alarmData))
            {
                _logger.Error($"Failed to load '{alarmsFilePath}', file is empty...");
                return;
            }

            Alarms = JsonStringSerializer.Deserialize <AlarmList>(alarmData);
            if (Alarms == null)
            {
                _logger.Error($"Failed to deserialize the alarms file '{alarmsFilePath}', make sure you don't have any json syntax errors.");
                return;
            }

            foreach (var item in Alarms)
            {
                item.Value.ForEach(x => x.ParseGeofenceFile());
            }
        }
Esempio n. 5
0
        public static List <Dictionary <object, object> > ListToDataTable(DataTable dt)
        {
            try
            {
                var serializer = new JsonStringSerializer();
                var dict       = new List <Dictionary <object, object> >();
                foreach (DataRow row in dt.Rows)
                {
                    var dic = new Dictionary <object, object>();

                    foreach (DataColumn col in dt.Columns)
                    {
                        var value = row[col];
                        if (value == DBNull.Value)
                        {
                            value = "";
                        }
                        else if (value.GetType() == typeof(byte[]))
                        {
                            value = serializer.DeserializeFromString <Dictionary <string, dynamic> >(Encoding.UTF8.GetString(value as byte[]));
                        }

                        dic[col.ColumnName] = value;
                    }
                    dict.Add(dic);
                }

                return(dict);
            }
            catch (Exception ex)
            {
                LogWriter.Error(ex.ToString());
                return(null);
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Saves the configuration file to the specified path.
        /// </summary>
        /// <param name="filePath">The full file path.</param>
        public void Save(string filePath)
        {
            //var serializedData = XmlStringSerializer.Serialize(this);
            var serializedData = JsonStringSerializer.Serialize(this);

            File.WriteAllText(filePath, serializedData);
        }
Esempio n. 7
0
        public async Task Create_UserDoesExist_CreatedAtRoute()
        {
            // Arrange
            var user  = MockApplicationUsers.Get(8);
            var token = await GetToken(user);

            const string createPath = Routes.TodoRoute;

            _endSystems.SetBearerToken(token);
            var model = new CreateTodoViewModel
            {
                Description = "I am your doctor, when you need, want some coke? Have some weed",
                Due         = new DateTime(2000, 1, 1)
            };
            var body    = JsonStringBuilder.CreateTodoJsonBody(model.Description, model.Due.ToString());
            var content = new StringContent(body);

            // Act
            var createResponse = await _endSystems.Post(createPath, content);

            var location    = createResponse.Headers.Location.ToString();
            var getResponse = await _endSystems.Get(location);

            var dto = JsonStringSerializer.GetTodoDto(getResponse.Body);

            // Assert
            Assert.Equal(HttpStatusCode.Created, createResponse.Code);
            Assert.Equal(HttpStatusCode.OK, getResponse.Code);
            Assert.Equal(model.Description, dto.Description);
            Assert.Equal(model.Due, dto.Due);

            // Tear down
            _endSystems.Dispose();
        }
Esempio n. 8
0
        /// <summary>
        /// Loads the configuration file from the specified path.
        /// </summary>
        /// <param name="filePath">The full file path.</param>
        /// <returns>Returns the deserialized Config object.</returns>
        public static Config Load(string filePath)
        {
            try
            {
                var data = File.ReadAllText(filePath);
                //return XmlStringSerializer.Deserialize<Config>(data);
                return(JsonStringSerializer.Deserialize <Config>(data));
            }
            catch (Exception ex)
            {
                Utils.LogError(ex);
            }

            return(null);
        }
Esempio n. 9
0
        public async Task Edit_ExistingTodoOwnedByTokenOwner_Ok()
        {
            // Arrange
            var user       = MockApplicationUsers.Get(2);
            var todoToEdit = MockTodos.GetAll().LastOrDefault(z => z.Owner.Id == user.Id);

            Assert.NotNull(todoToEdit);
            var token = await GetToken(user);

            var model = new EditTodoViewModel
            {
                Id          = todoToEdit.Id,
                Due         = new DateTime(2014, 12, 12, 10, 11, 12),
                Description = "It's like a jungle sometimes - It makes me wonder how I keep from goin' under"
            };
            var body = JsonStringBuilder.EditTodoJsonBody(
                model.Description, model.Due.ToString(), model.Id.ToString());
            var content = new StringContent(body);

            _endSystems.SetBearerToken(token);
            var getPath = $"{Routes.TodoRoute}/{model.Id}";
            var putPath = Routes.TodoRoute;

            // Act
            var getResponse1 = await _endSystems.Get(getPath);

            var editResponse = await _endSystems.Put(putPath, content);

            var getResponse2 = await _endSystems.Get(getPath);

            var dtoBefore = JsonStringSerializer.GetTodoDto(getResponse1.Body);
            var dtoAfter  = JsonStringSerializer.GetTodoDto(getResponse2.Body);

            // Assert
            Assert.Equal(HttpStatusCode.OK, getResponse1.Code);
            Assert.Equal(HttpStatusCode.OK, editResponse.Code);
            Assert.Equal(HttpStatusCode.OK, getResponse2.Code);
            Assert.Equal(todoToEdit.Id, dtoBefore.Id);
            Assert.Equal(todoToEdit.Due, dtoBefore.Due);
            Assert.Equal(todoToEdit.Description, dtoBefore.Description);
            Assert.Equal(model.Id, dtoAfter.Id);
            Assert.Equal(model.Due, dtoAfter.Due);
            Assert.Equal(model.Description, dtoAfter.Description);

            // Tear down
            _endSystems.Dispose();
        }
Esempio n. 10
0
        /// <summary>
        /// Loads the configuration file from the specified path.
        /// </summary>
        /// <param name="filePath">The full file path.</param>
        /// <returns>Returns the deserialized Config object.</returns>
        public static Database Load(string filePath)
        {
            try
            {
                if (File.Exists(filePath))
                {
                    var data = File.ReadAllText(filePath);
                    //return XmlStringSerializer.Deserialize<Database>(data);
                    return(JsonStringSerializer.Deserialize <Database>(data));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"LoadConfig: {ex}");
            }

            return(new Database());
        }
Esempio n. 11
0
        public async Task GetAllUsers_AdminRequesting_OkWithAllUsersInOrder()
        {
            // Arrange
            var          requestingUser = MockApplicationUsers.Get(0);
            const string path           = Routes.UserRoute;
            var          token          = await GetToken(requestingUser);

            _endSystems.SetBearerToken(token);
            var expectedDtos =
                MockApplicationUsers
                .GetAll()
                .OrderBy(w => w.Name)
                .Select(z => new ApplicationUserDto(z))
                .ToArray();
            var first = true;
            ApplicationUserDto last = null;

            // Act
            var response = await _endSystems.Get(path);

            var dtos = JsonStringSerializer.GetListOfApplicationUserDto(response.Body);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.Code);
            Assert.Equal(expectedDtos.Length, dtos.Length);
            for (var i = 0; i < dtos.Length; i++)
            {
                Assert.Equal(expectedDtos[i].Id, dtos[i].Id);
                Assert.Equal(expectedDtos[i].Email, dtos[i].Email);
                Assert.Equal(expectedDtos[i].Name, dtos[i].Name);
                if (first)
                {
                    first = false;
                }
                else
                {
                    Assert.True(string.Compare(dtos[i].Name, last.Name, StringComparison.Ordinal) >= 0);
                }
                last = dtos[i];
            }

            // Tear down
            _endSystems.Dispose();
        }
Esempio n. 12
0
        public async Task GetAllTodos_UserHasTokenDateQueryInvalid_OkAndEmptyDtoArray()
        {
            // Arrange
            var user  = MockApplicationUsers.Get(2);
            var path  = $"{Routes.TodoRoute}?year=2017&month=15&day=33";
            var token = await GetToken(user);

            _endSystems.SetBearerToken(token);

            // Act
            var response = await _endSystems.Get(path);

            var dtos = JsonStringSerializer.GetListOfTodoto(response.Body);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.Code);
            Assert.Empty(dtos);

            // Tear down
            _endSystems.Dispose();
        }
Esempio n. 13
0
        public async Task GetAllTodos_UserHasTokenValidQuery_OkAndFilteredDtoArray()
        {
            // Arrange
            var user  = MockApplicationUsers.Get(4);
            var todos = MockTodos
                        .GetAll()
                        .Where(w => w.Owner.Id == user.Id)
                        .OrderBy(w => w.Due)
                        .ToArray();

            Assert.True(todos.Length > 1);
            var filterDate = todos[0].Due.Date;

            Assert.NotEqual(todos[0].Due.Date, todos[1].Due.Date);
            var filteredTodos = MockTodos
                                .GetAll()
                                .Where(w => w.Owner.Id == user.Id && w.Due.Date == filterDate)
                                .OrderBy(w => w.Due)
                                .ToArray();

            Assert.NotEqual(todos.Length, filteredTodos.Length);
            var path  = $"{Routes.TodoRoute}?year={filterDate.Year}&month={filterDate.Month}&day={filterDate.Day}";
            var token = await GetToken(user);

            _endSystems.SetBearerToken(token);

            // Act
            var response = await _endSystems.Get(path);

            var dtos = JsonStringSerializer.GetListOfTodoto(response.Body);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.Code);
            Assert.NotEqual(todos.Length, dtos.Length);
            CheckOrderAndEqual(filteredTodos, dtos);

            // Tear down
            _endSystems.Dispose();
        }
Esempio n. 14
0
        public Database()
        {
            Reminders     = new ConcurrentDictionary <ulong, List <Reminder> >();
            Subscriptions = new List <Subscription <Pokemon> >();

            var pokemonDb = Path.Combine(DataFolderName, PokemonDatabaseFileName);

            if (File.Exists(pokemonDb))
            {
                var pokeDb = File.ReadAllText(pokemonDb);
                if (!string.IsNullOrEmpty(pokeDb))
                {
                    Pokemon = JsonStringSerializer.Deserialize <Dictionary <string, PokemonInfo> >(pokeDb);
                }
            }

            var movesetDb = Path.Combine(DataFolderName, MovesetDatabaseFileName);

            if (File.Exists(movesetDb))
            {
                var movesDb = File.ReadAllText(movesetDb);
                if (!string.IsNullOrEmpty(movesDb))
                {
                    Movesets = JsonStringSerializer.Deserialize <Dictionary <string, Moveset> >(movesDb);
                }
            }

            var cpMultipliersDb = Path.Combine(DataFolderName, CpMultipliersFileName);

            if (File.Exists(cpMultipliersDb))
            {
                var multipliersDb = File.ReadAllText(cpMultipliersDb);
                if (!string.IsNullOrEmpty(multipliersDb))
                {
                    CpMultipliers = JsonStringSerializer.Deserialize <Dictionary <string, double> >(multipliersDb);
                }
            }
        }
Esempio n. 15
0
        public static async Task <T> UrlToInstnace <T>(string url, TimeSpan?expiryPeriod = null) where T : new()
        {
            try
            {
                var webStr = await WebHelper.GetWebStr(url, expiryPeriod); // Debug.WriteLine($"{url}:\r\n{txt}");      //T t = (T)Serializer.LoadFromStringMin<T>(xml);      return t;                                          //return StringToInstance<T>(xml);

                if (webStr.StartsWith("<"))
                {
                    return((T) new XmlSerializer(typeof(T)).Deserialize(new StringReader(webStr)));
                }
                if (webStr.StartsWith("[") || webStr.StartsWith("{"))
                {
                    return(JsonStringSerializer.Load <T>(webStr));                                         //needs what? (check BusCatch) ... probably C:\c\AsLink\PlatformNeutral\JsonHelper.cs
                }
                else
                {
                    Debug.WriteLine(/*ApplicationData.Current.RoamingSettings.Values["Exn"] = */ $"\r\nFAILED deserial-n: \r\n{url}\r\n{webStr}");
                }
            }
            catch (Exception ex) { ex.Log(); throw; }

            return(default(T)); // null
        }
Esempio n. 16
0
        public void DeserializeEmptyStringToNull()
        {
            IStringSerializer serializer = new JsonStringSerializer();

            Assert.IsNull(serializer.Deserialize <object>(string.Empty));
        }
Esempio n. 17
0
 public string ToJsonString()
 {
     return(JsonStringSerializer.Serialize(this));
 }
Esempio n. 18
0
        public static T JsonDeserialize <T>(string str)
        {
            var ser = new JsonStringSerializer();

            return(ser.DeserializeFromString <T>(str));
        }
Esempio n. 19
0
        public void SerializeNullObjectToNullString()
        {
            IStringSerializer serializer = new JsonStringSerializer();

            Assert.IsNull(serializer.Serialize <object>(null));
        }