public async Task <IActionResult> UpdateEstablishment([FromBody] ViewModels.Establishment item, string id)
        {
            if (item == null || string.IsNullOrEmpty(id) || id != item.id)
            {
                return(BadRequest());
            }

            // get the legal entity.
            Guid adoxio_establishmentid = GuidUtility.SafeGuidConvert(id);

            MicrosoftDynamicsCRMadoxioEstablishment adoxioEstablishment = _dynamicsClient.GetEstablishmentById(adoxio_establishmentid);

            if (adoxioEstablishment == null)
            {
                return(new NotFoundResult());
            }

            // we are doing a patch, so wipe out the record.
            adoxioEstablishment = new MicrosoftDynamicsCRMadoxioEstablishment();

            // copy values over from the data provided
            adoxioEstablishment.CopyValues(item);

            try
            {
                await _dynamicsClient.Establishments.UpdateAsync(adoxio_establishmentid.ToString(), adoxioEstablishment);
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, "Error updating establishment");
                throw new Exception("Unable to update establishment");
            }

            try
            {
                adoxioEstablishment = _dynamicsClient.GetEstablishmentById(adoxio_establishmentid);
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, "Error getting establishment");
                throw new Exception("Unable to get establishment after update");
            }

            return(new JsonResult(adoxioEstablishment.ToViewModel()));
        }
        public async Task <IActionResult> CreateEstablishment([FromBody] ViewModels.Establishment item)
        {
            // create a new legal entity.
            MicrosoftDynamicsCRMadoxioEstablishment adoxio_establishment = new MicrosoftDynamicsCRMadoxioEstablishment();

            // copy received values to Dynamics LegalEntity
            adoxio_establishment.CopyValues(item);
            try
            {
                adoxio_establishment = await _dynamicsClient.Establishments.CreateAsync(adoxio_establishment);
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, "Error creating establishment");
                throw new Exception("Unable to create establishment");
            }

            ViewModels.Establishment result = adoxio_establishment.ToViewModel();

            return(new JsonResult(result));
        }
        //[Fact]
        public async System.Threading.Tasks.Task TestCRUD()
        {
            string initialName = "InitialName";
            string changedName = "ChangedName";

            var loginUser = randomNewUserName("NewLoginUser", 6);
            var strId     = await LoginAndRegisterAsNewUser(loginUser);

            // C - Create
            var request = new HttpRequestMessage(HttpMethod.Post, "/api/" + service);

            ViewModels.Establishment viewmodel_adoxio_establishment = new ViewModels.Establishment()
            {
                Name = initialName
            };

            string jsonString = JsonConvert.SerializeObject(viewmodel_adoxio_establishment);

            request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");

            var response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            // parse as JSON.
            jsonString = await response.Content.ReadAsStringAsync();

            ViewModels.Establishment responseViewModel = JsonConvert.DeserializeObject <ViewModels.Establishment>(jsonString);

            // name should match.
            Assert.Equal(initialName, responseViewModel.Name);
            Guid id = new Guid(responseViewModel.id);

            // R - Read

            request  = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + id);
            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            jsonString = await response.Content.ReadAsStringAsync();

            responseViewModel = JsonConvert.DeserializeObject <ViewModels.Establishment>(jsonString);
            Assert.Equal(initialName, responseViewModel.Name);

            // U - Update
            ViewModels.Establishment patchModel = new ViewModels.Establishment()
            {
                Name = changedName
            };

            request = new HttpRequestMessage(HttpMethod.Put, "/api/" + service + "/" + id)
            {
                Content = new StringContent(JsonConvert.SerializeObject(patchModel), Encoding.UTF8, "application/json")
            };
            response = await _client.SendAsync(request);

            jsonString = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();

            // verify that the update persisted.

            request  = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + id);
            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            jsonString = await response.Content.ReadAsStringAsync();

            responseViewModel = JsonConvert.DeserializeObject <ViewModels.Establishment>(jsonString);
            Assert.Equal(changedName, responseViewModel.Name);

            // D - Delete

            request  = new HttpRequestMessage(HttpMethod.Post, "/api/" + service + "/" + id + "/delete");
            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            // second delete should return a 404.
            request  = new HttpRequestMessage(HttpMethod.Post, "/api/" + service + "/" + id + "/delete");
            response = await _client.SendAsync(request);

            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);

            // should get a 404 if we try a get now.
            request  = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + id);
            response = await _client.SendAsync(request);

            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);

            await LogoutAndCleanupTestUser(strId);
        }
        /// <summary>
        /// Convert a given voteQuestion to a ViewModel
        /// </summary>
        public static ViewModels.Establishment ToViewModel(this MicrosoftDynamicsCRMadoxioEstablishment adoxio_establishment)
        {
            ViewModels.Establishment result = null;
            if (adoxio_establishment != null)
            {
                result = new ViewModels.Establishment();
                if (adoxio_establishment.AdoxioEstablishmentid != null)
                {
                    result.id = adoxio_establishment.AdoxioEstablishmentid.ToString();
                }

                result._licencee_value      = GuidUtility.SafeNullableGuidConvert(adoxio_establishment._adoxioLicenceeValue);
                result._licencetypeid_value = GuidUtility.SafeNullableGuidConvert(adoxio_establishment._adoxioLicencetypeidValue);
                //result._municipality_value = GuidUtility.SafeNullableGuidConvert(adoxio_establishment._adoxioMunicipalityValue);
                result._policejurisdiction_value = GuidUtility.SafeNullableGuidConvert(adoxio_establishment._adoxioPdjurisdictionValue);
                result._primaryinspectorid_value = GuidUtility.SafeNullableGuidConvert(adoxio_establishment._adoxioPrimaryinspectoridValue);
                result._territory_value          = GuidUtility.SafeNullableGuidConvert(adoxio_establishment._adoxioTerritoryValue);
                result._createdby_value          = GuidUtility.SafeNullableGuidConvert(adoxio_establishment._createdbyValue);
                result._createdonbehalfby_value  = GuidUtility.SafeNullableGuidConvert(adoxio_establishment._createdonbehalfbyValue);
                result._modifiedby_value         = GuidUtility.SafeNullableGuidConvert(adoxio_establishment._modifiedbyValue);
                result._modifiedonbehalfby_value = GuidUtility.SafeNullableGuidConvert(adoxio_establishment._modifiedonbehalfbyValue);
                result._ownerid_value            = GuidUtility.SafeNullableGuidConvert(adoxio_establishment._owneridValue);
                result._owningbusinessunit_value = GuidUtility.SafeNullableGuidConvert(adoxio_establishment._owningbusinessunitValue);
                result._owningteam_value         = GuidUtility.SafeNullableGuidConvert(adoxio_establishment._owningteamValue);
                result._owninguser_value         = GuidUtility.SafeNullableGuidConvert(adoxio_establishment._owninguserValue);
                result.Addresscity              = adoxio_establishment.AdoxioAddresscity;
                result.Addresspostalcode        = adoxio_establishment.AdoxioAddresspostalcode;
                result.Addressstreet            = adoxio_establishment.AdoxioAddressstreet;
                result.Alreadyopen              = adoxio_establishment.AdoxioAlreadyopen;
                result.Email                    = adoxio_establishment.AdoxioEmail;
                result.Expectedopendate         = adoxio_establishment.AdoxioExpectedopendate;
                result.Fridayclose              = adoxio_establishment.AdoxioFridayclose;
                result.Fridayopen               = adoxio_establishment.AdoxioFridayopen;
                result.Hasduallicence           = adoxio_establishment.AdoxioHasduallicence;
                result.Isrural                  = adoxio_establishment.AdoxioIsrural;
                result.Isstandalonepatio        = adoxio_establishment.AdoxioIsstandalonepatio;
                result.Locatedatwinery          = adoxio_establishment.AdoxioLocatedatwinery;
                result.Locatedonfirstnationland = adoxio_establishment.AdoxioLocatedonfirstnationland;
                result.Mailsenttorestaurant     = adoxio_establishment.AdoxioMailsenttorestaurant;
                result.Mondayclose              = adoxio_establishment.AdoxioMondayclose;
                result.Mondayopen               = adoxio_establishment.AdoxioMondayopen;
                result.Name                = adoxio_establishment.AdoxioName;
                result.Occupantcapacity    = adoxio_establishment.AdoxioOccupantcapacity;
                result.Occupantload        = adoxio_establishment.AdoxioOccupantload;
                result.Parcelid            = adoxio_establishment.AdoxioParcelid;
                result.Patronparticipation = adoxio_establishment.AdoxioPatronparticipation;
                result.Phone               = adoxio_establishment.AdoxioPhone;
                result.Saturdayclose       = adoxio_establishment.AdoxioSaturdayclose;
                result.Saturdayopen        = adoxio_establishment.AdoxioSaturdayopen;
                result.Sendmailtoestablishmentuponapproval = adoxio_establishment.AdoxioSendmailtoestablishmentuponapproval;
                result.Standardhours             = adoxio_establishment.AdoxioStandardhours;
                result.Sundayclose               = adoxio_establishment.AdoxioSundayclose;
                result.Sundayopen                = adoxio_establishment.AdoxioSundayopen;
                result.Thursdayclose             = adoxio_establishment.AdoxioThursdayclose;
                result.Thursdayopen              = adoxio_establishment.AdoxioThursdayopen;
                result.Tuesdayclose              = adoxio_establishment.AdoxioTuesdayclose;
                result.Tuesdayopen               = adoxio_establishment.AdoxioTuesdayopen;
                result.Wednesdayclose            = adoxio_establishment.AdoxioWednesdayclose;
                result.Wednesdayopen             = adoxio_establishment.AdoxioWednesdayopen;
                result.Createdon                 = adoxio_establishment.Createdon;
                result.Importsequencenumber      = adoxio_establishment.Importsequencenumber;
                result.Modifiedon                = adoxio_establishment.Modifiedon;
                result.Overriddencreatedon       = adoxio_establishment.Overriddencreatedon;
                result.StatusCode                = adoxio_establishment.Statuscode;
                result.StateCode                 = adoxio_establishment.Statecode;
                result.Timezoneruleversionnumber = adoxio_establishment.Timezoneruleversionnumber;
                result.Utcconversiontimezonecode = adoxio_establishment.Utcconversiontimezonecode;
                result.IsOpen = adoxio_establishment.AdoxioIsopen;
                if (adoxio_establishment.Versionnumber != null)
                {
                    result.Versionnumber = adoxio_establishment.Versionnumber;
                }
            }
            return(result);
        }
        /// <summary>
        /// Copy values from a Dynamics establishme t entity to a view model.
        /// </summary>
        /// <param name="to"></param>
        /// <param name="from"></param>
        public static void CopyValues(this MicrosoftDynamicsCRMadoxioEstablishment to, ViewModels.Establishment from)
        {
            // Only copy email and phone number
            if (from.Email != null)
            {
                to.AdoxioEmail = from.Email;
            }

            if (from.Phone != null)
            {
                to.AdoxioPhone = from.Phone;
            }

            if (from.IsOpen != null)
            {
                to.AdoxioIsopen = from.IsOpen;
            }
        }