/// <summary>
		/// Returns a list of dynamic objects
		/// </summary>
		/// <param name="query">oData query</param>
		/// <returns></returns>
		public async Task<List<dynamic>> GetDynamicAsync(string query)
		{
			string response = await _conn.GetAsync(query);
            var jsonObject = await ApiResponseCleaner.GetJsonArrayAsync(response);

			var converter = new EntityConverter();
			List<dynamic> list = converter.ConvertJsonToDynamicObjectList(jsonObject);
			return list;
		}
        /// <summary>
        /// Returns a list of dynamic objects
        /// </summary>
        /// <param name="query">oData query</param>
        /// <returns></returns>
        public List<dynamic> GetDynamic(string query)
        {
            string response = _conn.Get(query);
            response = ApiResponseCleaner.GetJsonArray(response);

            var converter = new EntityConverter();
            List<dynamic> list = converter.ConvertJsonToDynamicObjectList(response);
            return list;
        }
        private void PutData()
        {
            // Get GUID and set it in property for PUT and Delete functions
            string response = _conn.Get("$filter=Code+eq+'SDKTest123456789'");
            response = ApiResponseCleaner.GetJsonArray(response);
            var converter = new EntityConverter();

            dynamic dresponse = converter.ConvertJsonToDynamicObjectList(response);
            string id = dresponse[0].ID;
            _conn.Put("ID", id, @"{""Description"":""UAT GLAccount""}");
        }
        public async Task <HttpResponseData> SearchExpired([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "testhooks/jobOps/searchExpired")] HttpRequestData req)
        {
            _log.Info("Search expired jobs");

            var jobs = await _jobOps.SearchExpired().ToListAsync();

            var msg  = JsonSerializer.Serialize(jobs, EntityConverter.GetJsonSerializerOptions());
            var resp = req.CreateResponse(HttpStatusCode.OK);
            await resp.WriteStringAsync(msg);

            return(resp);
        }
        private void btnModify_Click(object sender, RoutedEventArgs e)
        {
            if (!ValidationManager.Validate(this))
            {
                return;
            }

            if (string.IsNullOrEmpty(newVM.SettleSysNo))
            {
                Window.Alert("请先匹配可调整的结算单!");
                return;
            }

            Window.Confirm(ResConsignAdjustNew.InfoMsg_ConfirmModify, (obj, args) =>
            {
                if (args.DialogResult == DialogResultType.OK)
                {
                    ConsignAdjustInfo Info = EntityConverter <ConsignAdjustVM, ConsignAdjustInfo> .Convert(newVM);

                    if (null != Info.SysNo)
                    {
                        if (Info.ItemList.Count == 0)
                        {
                            Window.Alert("请至少添加一条扣款项信息");
                            return;
                        }

                        Info.TotalAmt = Info.ItemList.Sum(p => p.DeductAmt);
                        serviceFacade.Update(Info, (obj1, args1) =>
                        {
                            if (args1.FaultsHandle())
                            {
                                return;
                            }

                            if (args1.Result.SysNo > 0)
                            {
                                Window.Alert(ResConsignAdjustNew.AlertMsg_ModifySuc);
                            }
                            else
                            {
                                Window.Alert(ResConsignAdjustNew.AlertMsg_ModifyFailed);
                                return;
                            }
                        });
                    }
                    else
                    {
                        Window.Alert(ResConsignAdjustNew.AlertMsg_ModifySuc);
                    }
                }
            });
        }
Beispiel #6
0
        public static string SerializeEntityList(IList <Entity> list)
        {
            EntityConverter      converter = new EntityConverter();
            JavaScriptSerializer ser       = new JavaScriptSerializer();

            ser.MaxJsonLength = int.MaxValue;
            ser.RegisterConverters(new JavaScriptConverter[] { converter });

            string data = ser.Serialize(list);

            return("[" + data + "]");
        }
        public void EntityConverter_ConvertLinkedEntityJsonArrayToObjects_Succeeds()
        {
            string json                  = ApiResponseCleaner.GetJsonArray(JsonFileReader.GetJsonFromFile("Response_Json_Array_SalesInvoice_WithLinkedEntities.txt"));
            var    converter             = new EntityConverter();
            List <SalesInvoice> invoices = converter.ConvertJsonArrayToObjectList <SalesInvoice>(json);

            foreach (var invoice in invoices)
            {
                var sil = (List <SalesInvoiceLine>)invoice.SalesInvoiceLines;
                Assert.IsTrue(sil.Count > 0);
            }
        }
        public void EntityConverter_CreateWithGuid_Succeeds()
        {
            var newAccount = new Account {
                ID = new Guid("8f8b8025-90b3-4307-a8a3-a5111d048fb5")
            };
            var          entityConverter = new EntityConverter();
            const string expected        = "{\"ID\":\"8f8b8025-90b3-4307-a8a3-a5111d048fb5\"}";

            var result = entityConverter.ConvertObjectToJson(new Account(), newAccount, null);

            Assert.AreEqual(expected, result);
        }
Beispiel #9
0
        public void ConvertWithMappingAction()
        {
            List <Customer> customers = GetCustomers();

            EntityConverter <Customer, Contact> converter = new EntityConverter <Customer, Contact>((cu, co) => co.Phone = cu.Telephone);
            IList <Contact> contacts = converter.Convert(customers);

            Assert.AreEqual(100, contacts.Count);
            Assert.AreEqual("TestCustomer1", contacts[0].Name);
            Assert.AreEqual("TestAddress1", contacts[0].Address);
            Assert.AreEqual("555-1212", contacts[0].Phone);
        }
Beispiel #10
0
        public async Task Tags(SocketGuildUser user)
        {
            var avatar = EntityConverter.ConvertUser(user);
            var tags   = string.Join(", ", avatar.Tags);

            while (tags.Length > 0)
            {
                await ReplyAsync(tags.Substring(0, 2000));

                tags = tags.Substring(2000);
            }
        }
Beispiel #11
0
        public async Task RemoveCursed()
        {
            var account = EntityConverter.ConvertUser(Context.User);
            var inv     = account.Inv;

            if (inv.RemoveCursedEquipment())
            {
                UserAccountProvider.StoreUser(account);
                _ = ShowInventory();
            }
            await Task.CompletedTask;
        }
Beispiel #12
0
        public async Task Unequip([Remainder] string item)
        {
            var account = EntityConverter.ConvertUser(Context.User);
            var inv     = account.Inv;

            if (inv.Unequip(item))
            {
                UserAccountProvider.StoreUser(account);
                _ = ShowInventory();
            }
            await Task.CompletedTask;
        }
        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(queryVM.ProductSysNo) && string.IsNullOrEmpty(queryVM.ProductID))
            {
                Window.Alert("商品ID和商品编号,至少要填写一项!");
                return;
            }
            //搜索操作:
            filter = EntityConverter <PurchaseOrderQueryVM, PurchaseOrderQueryFilter> .Convert(this.queryVM);

            this.QueryResultGrid.Bind();
        }
        public void EntityConverter_ConvertObjectToJson_ForAlteredFields_Succeeds()
        {
            var account = new Account {
                Name = "New Account"
            };
            var          entityConverter = new EntityConverter();
            const string expected        = "{\"Name\":\"New Account\"}";

            var result = entityConverter.ConvertObjectToJson(new Account(), account, null);

            Assert.AreEqual(expected, result);
        }
Beispiel #15
0
        /// <summary>
        /// 查询Warehouse List
        /// </summary>
        /// <param name="queryFilter"></param>
        /// <param name="callback"></param>
        public void GetWarehouseListByCompanyCode(string companyCode, Action <List <WarehouseInfoVM> > callback)
        {
            string relativeUrl = "/InventoryService/Stock/WH/GetByCompanyCode";

            restClient.Query <List <WarehouseInfo> >(relativeUrl, companyCode, (obj, args) =>
            {
                if (!args.FaultsHandle())
                {
                    callback(EntityConverter <WarehouseInfo, WarehouseInfoVM> .Convert(args.Result));
                }
            });
        }
        public void EntityConverter_ConvertObjectToJson_WithReadonlyFields_Succeeds()
        {
            var newAccount = new Account {
                AccountManagerHID = 10
            };
            var          entityConverter = new EntityConverter();
            const string expected        = "";

            var result = entityConverter.ConvertObjectToJson(new Account(), newAccount, null);

            Assert.AreEqual(expected, result);
        }
        public async Task <HttpResponseData> GetMonitorSettings([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "testhooks/logAnalytics/monitorSettings")] HttpRequestData req)
        {
            _log.Info("Get monitor settings");

            var monitorSettings = await _logAnalytics.GetMonitorSettings();

            var msg  = JsonSerializer.Serialize(monitorSettings, EntityConverter.GetJsonSerializerOptions());
            var resp = req.CreateResponse(HttpStatusCode.OK);
            await resp.WriteStringAsync(msg);

            return(resp);
        }
        public void EntityConverter_CreateWithoutGuid_Succeeds()
        {
            var newAccount = new Account {
                ID = new Guid()
            };
            var          entityConverter = new EntityConverter();
            const string expected        = "";

            var result = entityConverter.ConvertObjectToJson(new Account(), newAccount, null);

            Assert.AreEqual(expected, result);
        }
Beispiel #19
0
        //创建供应商信息
        public void CreateVendor(VendorInfoVM newVendorInfoVM, EventHandler <RestClientEventArgs <VendorInfo> > callback)
        {
            VendorInfo vendorInfo = EntityConverter <VendorInfoVM, VendorInfo> .Convert(newVendorInfoVM);

            vendorInfo.CompanyCode     = CPApplication.Current.CompanyCode;
            vendorInfo.CreateUserSysNo = CPApplication.Current.LoginUser.UserSysNo;
            vendorInfo.CreateUserName  = CPApplication.Current.LoginUser.DisplayName;

            string relativeUrl = "/POService/Vendor/CreateVendor";

            restClient.Create <VendorInfo>(relativeUrl, vendorInfo, callback);
        }
Beispiel #20
0
        public async Task ShowInventory(Detail detail = Detail.None)
        {
            var split = new Dictionary <Detail, char>
            {
                { Detail.None, '>' },
                { Detail.Names, ',' },
                { Detail.NameAndPrice, '\n' }
            };
            var account = EntityConverter.ConvertUser(Context.User);
            var inv     = account.Inv;
            var embed   = new EmbedBuilder()
                          .AddField("Warrior Gear", inv.GearToString(ArchType.Warrior), true)
                          .AddField("Mage Gear", inv.GearToString(ArchType.Mage), true);

            var invstring = inv.InventoryToString(detail);

            if (invstring.Length >= 1024)
            {
                var remainingstring = invstring;
                var parts           = new List <string>();
                while (remainingstring.Length >= 1024)
                {
                    var lastitem = remainingstring.Take(1024).ToList().FindLastIndex(s => s.Equals(split[detail])) + 1;
                    parts.Add(string.Join("", remainingstring.Take(lastitem)));
                    remainingstring = string.Join("", remainingstring.Skip(lastitem));
                }

                parts.Add(remainingstring);
                foreach (var(value, index) in parts.Select((v, i) => (v, i)))
                {
                    embed.AddField($"Inventory ({index + 1}/{parts.Count})", value);
                }
            }
            else
            {
                embed.AddField("Inventory", invstring);
            }

            if (inv.GetChestsToString().Length > 0)
            {
                embed.AddField("Chests:", inv.GetChestsToString());
            }

            var fb = new EmbedFooterBuilder();

            fb.WithText(
                $"{inv.Count} / {inv.MaxInvSize} {(inv.Upgrades < 4 ? $"Upgrade: {50000 * Math.Pow(2, inv.Upgrades)}" : "")}");
            embed.AddField("Coin", $"{Emotes.GetIcon("Coin")} {inv.Coins}");
            embed.WithColor(Colors.Get("Iodem"));
            embed.WithFooter(fb);
            await Context.Channel.SendMessageAsync("", false, embed.Build());
        }
        protected virtual async Task AddPlayer(SocketReaction reaction)
        {
            if (PlayerMessages.Values.Any(s => (s.Id == reaction.UserId)))
            {
                return;
            }
            SocketGuildUser player       = (SocketGuildUser)reaction.User.Value;
            var             playerAvatar = EntityConverter.ConvertUser(player);

            var p = Factory.CreatePlayerFighter(playerAvatar);

            await AddPlayer(p);
        }
Beispiel #22
0
        public async Task <HttpResponseData> ListInstanceIds([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "testhooks/vmssOperations/listInstanceIds")] HttpRequestData req)
        {
            _log.Info("list instance ids");
            var query = UriExtension.GetQueryComponents(req.Url);
            var name  = UriExtension.GetGuid("name", query) ?? throw new Exception("name must be set");
            var ids   = await _vmssOps.ListInstanceIds(name);

            var json = JsonSerializer.Serialize(ids, EntityConverter.GetJsonSerializerOptions());
            var resp = req.CreateResponse(HttpStatusCode.OK);
            await resp.WriteStringAsync(json);

            return(resp);
        }
Beispiel #23
0
        public async Task <HttpResponseData> SendEvent([HttpTrigger(AuthorizationLevel.Anonymous, "put", Route = "testhooks/events/sendEvent")] HttpRequestData req)
        {
            _log.Info("Send event");

            var s = await req.ReadAsStringAsync();

            var msg = JsonSerializer.Deserialize <EventMessage>(s !, EntityConverter.GetJsonSerializerOptions());
            await _events.SendEvent(msg !.Event);

            var resp = req.CreateResponse(HttpStatusCode.OK);

            return(resp);
        }
Beispiel #24
0
        /// <summary>
        /// Gets a legal <see cref="PKM"/> from a random in-game encounter's data.
        /// </summary>
        /// <param name="tr">Trainer Data to use in generating the encounter</param>
        /// <param name="species">Species ID to generate</param>
        /// <param name="form">Form to generate; if left null, picks first encounter</param>
        /// <param name="shiny"></param>
        /// <param name="alpha"></param>
        /// <param name="attempt"></param>
        /// <param name="pk">Result legal pkm</param>
        /// <returns>True if a valid result was generated, false if the result should be ignored.</returns>
        public static bool GetRandomEncounter(this ITrainerInfo tr, int species, int?form, bool shiny, bool alpha, ref int attempt, out PKM?pk)
        {
            var blank = EntityBlank.GetBlank(tr);

            pk = GetRandomEncounter(blank, tr, species, form, shiny, alpha, ref attempt);
            if (pk == null)
            {
                return(false);
            }

            pk = EntityConverter.ConvertToType(pk, blank.GetType(), out _);
            return(pk != null);
        }
Beispiel #25
0
        public async Task PatDown([Remainder] SocketGuildUser user = null)
        {
            var account = EntityConverter.ConvertUser(user);

            await Context.Channel.SendMessageAsync(embed :
                                                   new EmbedBuilder()
                                                   .WithAuthor(user)
                                                   .AddField("Account Created", user.CreatedAt)
                                                   .AddField("User Joined", user.JoinedAt)
                                                   .AddField("Status", user.Status, true)
                                                   .AddField("Last Activity", account.LastXP)
                                                   .Build());
        }
Beispiel #26
0
        /// <summary>
        /// Method to get user profile
        /// </summary>
        /// <param name="userDTO"></param>
        /// <returns></returns>
        public IUserDTO GetProfile(IUserDTO userDTO)
        {
            using (var context = new BufferOverflowDBEntities())
            {
                var user = context.User.SingleOrDefault(u => u.Id == userDTO.Id);
                if (user != null)
                {
                    EntityConverter.FillDTOFromEntity(user, userDTO);
                }

                return((userDTO.Id != 0) ? userDTO : null);
            }
        }
Beispiel #27
0
 public Events(IQueue queue, IWebhookOperations webhook, ILogTracer log, IContainers containers, ICreds creds)
 {
     _queue      = queue;
     _webhook    = webhook;
     _log        = log;
     _containers = containers;
     _creds      = creds;
     _options    = new JsonSerializerOptions(EntityConverter.GetJsonSerializerOptions())
     {
         DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
     };
     _options.Converters.Add(new RemoveUserInfo());
 }
        public async Task <HttpResponseData> DeleteNode([HttpTrigger(AuthorizationLevel.Anonymous, "delete", Route = "testhooks/nodeOperations/node")] HttpRequestData req)
        {
            _log.Info("delete node");
            var s = await req.ReadAsStringAsync();

            var node = JsonSerializer.Deserialize <Node>(s !, EntityConverter.GetJsonSerializerOptions());

            var r    = _nodeOps.Delete(node !);
            var resp = req.CreateResponse(HttpStatusCode.OK);
            await resp.WriteAsJsonAsync(r);

            return(resp);
        }
Beispiel #29
0
        public async Task ShinyDjinn(SocketGuildUser user, bool shiny, [Remainder] string djinn)
        {
            var acc         = EntityConverter.ConvertUser(user);
            var userDjinn   = acc.DjinnPocket;
            var chosenDjinn = userDjinn.GetDjinn(djinn);

            if (chosenDjinn == null)
            {
                return;
            }
            chosenDjinn.IsShiny = shiny;
            UserAccountProvider.StoreUser(acc);
        }
Beispiel #30
0
        public static IList <Entity> DeserializeEntityList(Entity entity, string json)
        {
            EntityConverter converter = (entity == null) ? new EntityConverter() : new EntityConverter(entity);

            IList <Entity>       list = new List <Entity>();
            JavaScriptSerializer ser  = new JavaScriptSerializer();

            ser.MaxJsonLength = int.MaxValue;
            ser.RegisterConverters(new JavaScriptConverter[] { converter });
            list = (List <Entity>)ser.Deserialize(json, typeof(IList <Entity>));

            return(list);
        }
Beispiel #31
0
    public async Task <T?> GetSecretObj <T>(Uri secretUrl)
    {
        var secret = await GetSecret(secretUrl);

        if (secret is null)
        {
            return(default(T));
        }
        else
        {
            return(JsonSerializer.Deserialize <T>(secret.Value, EntityConverter.GetJsonSerializerOptions()));
        }
    }
        public async Task <HttpResponseData> MarkTasksStoppedEarly([HttpTrigger(AuthorizationLevel.Anonymous, "patch", Route = "testhooks/nodeOperations/markTasksStoppedEarly")] HttpRequestData req)
        {
            _log.Info("mark tasks stopped early");

            var s = await req.ReadAsStringAsync();

            var markTasks = JsonSerializer.Deserialize <MarkTasks>(s !, EntityConverter.GetJsonSerializerOptions());
            await _nodeOps.MarkTasksStoppedEarly(markTasks !.node, markTasks.error);

            var resp = req.CreateResponse(HttpStatusCode.OK);

            return(resp);
        }
Beispiel #33
0
        private void DeleteData()
        {
            // Get GUID and set it in property for PUT and Delete functions
            string response = _conn.Get("$filter=Code+eq+'SDKTest123456789'");

            response = ApiResponseCleaner.GetJsonArray(response);
            var converter = new EntityConverter();

            dynamic dresponse = converter.ConvertJsonToDynamicObjectList(response);
            string  id        = dresponse[0].ID;

            _conn.Delete("ID", id);
        }
 public void EntityConverter_ConvertLongJson_Fails()
 {
     var entityConverter = new EntityConverter();
     string json = JsonFileReader.GetJsonFromFile("Response_Json_Array_Account_Long.txt");
     var accounts = entityConverter.ConvertJsonArrayToObjectList<Account>(json);
 }
        public void EntityConverter_ConvertLinkedObjectToJson_Succeeds()
        {
            // Create Object
            var newInvoice = new ComplexEntity
                {
                    Currency = "EUR",
                    OrderDate = new DateTime(2012, 10, 26),
                    InvoiceTo = new Guid("3734121e-1544-4b77-9ae2-7203e9bd6046"),
                    Journal = "50",
                    OrderedBy = new Guid("3734121e-1544-4b77-9ae2-7203e9bd6046"),
                    Description = "NewInvoiceForEntityWithCollection"
                };

            var newInvoiceLine = new ComplexEntityLine
                {
                    Description = "NewInvoiceForEntityWithCollection",
                    Item = new Guid("4f68481a-7a2c-4fbc-a3a0-0c494df3fa0d")
                };

            var invoicelines = new List<ComplexEntityLine> { newInvoiceLine };
            newInvoice.Lines = invoicelines;

            var entityConverter = new EntityConverter();
            string json = entityConverter.ConvertObjectToJson(newInvoice, null);
            string expected = JsonFileReader.GetJsonFromFileWithoutWhiteSpace("Expected_Json_Object_ComplexEntity_WithLinkedEntity.txt");
            Assert.AreEqual(expected, json);
        }
        public void EntityConverter_ConvertLinkedEntityJsonToObject_Succeeds()
        {
            string json = ApiResponseCleaner.GetJsonObject(JsonFileReader.GetJsonFromFile("Response_Json_Object_SalesInvoice.txt"));

            var converter = new EntityConverter();
            var invoice = converter.ConvertJsonToObject<SalesInvoice>(json);
            var lines = (List<SalesInvoiceLine>)invoice.SalesInvoiceLines;

            Assert.IsNotNull(invoice);
            Assert.IsTrue(lines.Count > 0);
        }
 public void Setup()
 {
     _entityConverter = new EntityConverter();
 }
        public void EntityConverter_CreateWithGuid_Succeeds()
        {
            var newAccount = new Account { ID = new Guid("8f8b8025-90b3-4307-a8a3-a5111d048fb5") };
            var entityConverter = new EntityConverter();
            const string expected = "{\"ID\":\"8f8b8025-90b3-4307-a8a3-a5111d048fb5\"}";

            var result = entityConverter.ConvertObjectToJson(new Account(), newAccount, null);

            Assert.AreEqual(expected, result);
        }
        public void EntityConverter_ConvertObjectToJson_ForNoAlteredFields_Succeeds()
        {
            var oldAccount = new Account { Name = "New Account" };
            var newAccount = new Account { Name = "New Account" };
            var entityConverter = new EntityConverter();
            const string expected = "";

            var result = entityConverter.ConvertObjectToJson(oldAccount, newAccount, null);

            Assert.AreEqual(expected, result);
        }
        private void ParseObjectList()
        {
            var converter = new EntityConverter();

            for (int i = 0; i < 100; i++)
            {
                string json = ApiResponseCleaner.GetJsonArray(JsonArray);
                List<Account> accounts = converter.ConvertJsonArrayToObjectList<Account>(json);
                if (accounts.Count != 2)
                {
                    throw new Exception("The count of the list isn't equal to the actual list");
                }
            }
        }
        public void ParseObjectList_LinkedEntities()
        {
            var converter = new EntityConverter();

            for (int i = 0; i < 100; i++)
            {
                string json = ApiResponseCleaner.GetJsonArray(LinkedEntities);
                List<SalesInvoice> invoices = converter.ConvertJsonArrayToObjectList<SalesInvoice>(json);

                foreach (var invoice in invoices)
                {
                    var sil = (List<SalesInvoiceLine>)invoice.SalesInvoiceLines;
                    Assert.IsTrue(sil.Count > 0);
                }
            }
        }
        public void EntityConverter_ConvertObjectToJson_ForAlteredFields_Succeeds()
        {
            var account = new Account{ Name = "New Account"};
            var entityConverter = new EntityConverter();
            const string expected = "{\"Name\":\"New Account\"}";

            var result = entityConverter.ConvertObjectToJson(new Account(), account, null);

            Assert.AreEqual(expected, result);
        }
        public void EntityConverter_ConvertObjectToJson_ForCreating_Succeeds()
        {
            // Test if objects is converted to json correctly
            var dateTimeEpoc = new DateTime(1970, 1, 1, 0, 0, 0, 0);

            #region Client Object and Json

            var simpleEntity = new SimpleEntity()
            {
                Code = "123",
                Description = "FOO",
                Id = new Guid("53697fab-137f-4242-b710-0139886b50f4"),
                StartDate = dateTimeEpoc.AddMilliseconds(1387188617287),
                EndDate = null,
                Boolean = true,
                NullableBoolean = null,
                Integer = 5,
                NullableInteger = null
            };

            const string expected = "{\"Code\":\"123\",\"Description\":\"FOO\",\"Id\":\"53697fab-137f-4242-b710-0139886b50f4\",\"StartDate\":\"2013-12-16T10:10:17.287\",\"EndDate\":null,\"Boolean\":true,\"NullableBoolean\":null,\"Integer\":5,\"NullableInteger\":null}";
            #endregion

            var converter = new EntityConverter();
            string result = converter.ConvertObjectToJson(simpleEntity, null);

            Assert.AreEqual(expected, result);
        }
        public void EntityConverter_ConvertEmptyLinkedObjectToJson_Succeeds()
        {
            // Create Object
            var newInvoice = new ComplexEntity
                {
                    Currency = "EUR",
                    OrderDate = new DateTime(2012, 10, 26),
                    InvoiceTo = new Guid("3734121e-1544-4b77-9ae2-7203e9bd6046"),
                    Journal = "50",
                    OrderedBy = new Guid("3734121e-1544-4b77-9ae2-7203e9bd6046"),
                    Description = "NewInvoiceForEntityWithCollection"
                };

            var entityConverter = new EntityConverter();
            string json = entityConverter.ConvertObjectToJson(newInvoice, null);
            string expected = JsonFileReader.GetJsonFromFileWithoutWhiteSpace("Expected_Json_Object_ComplexEntity_WithEmptyLinkedEntities.txt");
            Assert.AreEqual(expected, json);
        }
        public void EntityConverter_ConvertObjectToJson_WithReadonlyFields_Succeeds()
        {
            var newAccount = new Account { AccountManagerHID = 10 };
            var entityConverter = new EntityConverter();
            const string expected = "";

            var result = entityConverter.ConvertObjectToJson(new Account(), newAccount, null);

            Assert.AreEqual(expected, result);
        }
        public void EntityConverter_ConvertExistingLinkedObjectToJson_Succeeds()
        {
            // Create Object
            var newInvoice = new SalesInvoice {InvoiceID = new Guid("4f68481a-7a2c-4fbc-a3a0-0c494df3fa0d")};
            var newInvoiceLine = new SalesInvoiceLine {Description = "NewInvoiceForEntityWithCollection"};
            newInvoice.SalesInvoiceLines = new List<SalesInvoiceLine> { newInvoiceLine };

            //ControllerSingleton.GetInstance(new MockObjects.MAPIConnector_Controller(), "www.dummy.com/");
            var entityController = new EntityController(newInvoice, "ID", "4f68481a-7a2c-4fbc-a3a0-0c494df3fa0d", new MockObjects.ApiConnectionMock(), null);
            newInvoiceLine.Description = "ChangedNewInvoiceForEntityWithCollection";

            var entityConverter = new EntityConverter();
            var controllerDelegate = new GetEntityController(GetEntityController);
            string json = entityConverter.ConvertObjectToJson((SalesInvoice)entityController.OriginalEntity, newInvoice, controllerDelegate);

            const string expected = "{\"SalesInvoiceLines\": [{\"Description\": \"ChangedNewInvoiceForEntityWithCollection\"}]}";
            Assert.AreEqual(expected, json);

            throw new NotImplementedException();
        }
        public void EntityConverter_CreateWithoutGuid_Succeeds()
        {
            var newAccount = new Account { ID = new Guid() };
            var entityConverter = new EntityConverter();
            const string expected = "";

            var result = entityConverter.ConvertObjectToJson(new Account(), newAccount, null);

            Assert.AreEqual(expected, result);
        }
        public void EntityConverter_ConvertLinkedEntityJsonArrayToObjects_Succeeds()
        {
            string json = ApiResponseCleaner.GetJsonArray(JsonFileReader.GetJsonFromFile("Response_Json_Array_SalesInvoice_WithLinkedEntities.txt"));
            var converter = new EntityConverter();
            List<SalesInvoice> invoices = converter.ConvertJsonArrayToObjectList<SalesInvoice>(json);

            foreach (var invoice in invoices)
            {
                var sil = (List<SalesInvoiceLine>)invoice.SalesInvoiceLines;
                Assert.IsTrue(sil.Count > 0);
            }
        }
        /// <summary>
        /// Updates the entity
        /// </summary>
        /// <returns>True if the entity is updated</returns>
        public Boolean Update(object entity)
        {
            // Convert object to json
            var converter = new EntityConverter();
            string json = converter.ConvertObjectToJson(OriginalEntity, entity, _entityControllerDelegate);

            // Update entire object
            Boolean returnValue = false;

            // Update and set _originalentity to current entity (_entity)
            if (_connection.Put(_keyName, _identifier, json))
            {
                returnValue = true;
                OriginalEntity = Clone(entity);
            }
            return returnValue;
        }
		public async Task EntityConverter_ConvertLongJson_Fails()
		{
            // This failed for another reason in the original code, not because it was to long. Not clear to me why this should fail.
            var entityConverter = new EntityConverter();
			string json = JsonFileReader.GetJsonFromFile("Response_Json_Array_Account_Long.txt");
			var accounts = entityConverter.ConvertJsonArrayToObjectList<Account>(await ApiResponseCleaner.GetJsonArrayAsync(json));
		}