public async Task <IActionResult> CreateEquipment(string applicationType, [FromBody] ViewModels.Equipment item)
        {
            // get UserSettings from the session
            string       temp         = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
            UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(temp);

            // first check to see that a Equipment exists.
            string ApplicationSiteminderGuid = userSettings.SiteMinderGuid;

            if (ApplicationSiteminderGuid == null || ApplicationSiteminderGuid.Length == 0)
            {
                _logger.LogError(LoggingEvents.Error, "No Equipment Siteminder Guid exernal id");
                throw new Exception("Error. No ApplicationSiteminderGuid exernal id");
            }

            // create a new Equipment.
            MicrosoftDynamicsCRMbcgovEquipment equipment = new MicrosoftDynamicsCRMbcgovEquipment();

            equipment.CopyValues(item);

            try
            {
                equipment = await _dynamicsClient.Equipments.CreateAsync(equipment);
            }
            catch (OdataerrorException odee)
            {
                _logger.LogError("Error creating Equipment");
                _logger.LogError("Request:");
                _logger.LogError(odee.Request.Content);
                _logger.LogError("Response:");
                _logger.LogError(odee.Response.Content);
                throw new OdataerrorException("Error creating Equipment");
            }
            return(Json(equipment.ToViewModel()));
        }
        public IActionResult GetEquipment(string id)
        {
            ViewModels.Equipment result = null;

            if (!string.IsNullOrEmpty(id) && Guid.TryParse(id, out Guid equipmentId))
            {
                // query the Dynamics system to get the Equipment record.
                MicrosoftDynamicsCRMbcgovEquipment equipment = _dynamicsClient.GetEquipmentByIdWithChildren(equipmentId);

                if (equipment != null)
                {
                    result = equipment.ToViewModel();
                }
                else
                {
                    return(new NotFoundResult());
                }
            }
            else
            {
                return(BadRequest());
            }

            return(Json(result));
        }
        public IActionResult DeleteEquipment(string id)
        {
            _logger.LogDebug(LoggingEvents.HttpPost, "Begin method " + this.GetType().Name + "." + MethodBase.GetCurrentMethod().ReflectedType.Name);

            if (!string.IsNullOrEmpty(id) && Guid.TryParse(id, out Guid equipmentId))
            {
                MicrosoftDynamicsCRMbcgovEquipment equipment = _dynamicsClient.GetEquipmentById(equipmentId);
                if (equipment == null)
                {
                    _logger.LogWarning(LoggingEvents.NotFound, "Equipment NOT found.");
                    return(new NotFoundResult());
                }

                // TODO - add this routine.

                /*
                 * if (!UserDynamicsExtensions.CurrentUserHasAccessToEquipment(equipmentId, _httpContextAccessor, _dynamicsClient))
                 * {
                 *  _logger.LogWarning(LoggingEvents.NotFound, "Current user has NO access to the equipment.");
                 *  return new NotFoundResult();
                 * }
                 */

                // delete the equipment
                try
                {
                    _dynamicsClient.Equipments.Delete(equipmentId.ToString());
                    _logger.LogDebug(LoggingEvents.HttpDelete, "Equipment deleted: " + equipmentId.ToString());
                }
                catch (OdataerrorException odee)
                {
                    _logger.LogError(LoggingEvents.Error, "Error deleting the equipment: " + equipmentId.ToString());
                    _logger.LogError("Request:");
                    _logger.LogError(odee.Request.Content);
                    _logger.LogError("Response:");
                    _logger.LogError(odee.Response.Content);
                    throw new OdataerrorException("Error deleting the account: " + equipmentId.ToString());
                }

                _logger.LogDebug(LoggingEvents.HttpDelete, "No content returned.");
                return(NoContent()); // 204
            }
            else
            {
                return(BadRequest());
            }
        }
 public static void CopyValues(this MicrosoftDynamicsCRMbcgovEquipment to, ViewModels.Equipment from)
 {
     // Equipment Information
     to.BcgovEquipmenttype      = (int?)from.EquipmentType;
     to.BcgovEquipmenttypeother = from.EquipmentTypeOther;
     to.BcgovName = from.Name;
     to.BcgovPillpressencapsulatorsize      = (int?)from.PillpressEncapsulatorSize;
     to.BcgovPillpressencapsulatorsizeother = from.PillpressEncapsulatorSizeOther;
     to.BcgovLevelofautomation    = (int?)from.LevelOfEquipmentAutomation;
     to.BcgovPillpressmaxcapacity = from.PillpressMaxCapacity;
     to.BcgovHowwasequipmentbuilt = (int?)from.HowWasEquipmentBuilt;
     // to.BcgovHowwasequipmentbuiltother = from.HowWasEquipmentBuiltOther;
     to.BcgovNameofmanufacturer = from.NameOfManufacturer;
     to.BcgovMake                             = from.EquipmentMake;
     to.BcgovModel                            = from.EquipmentModel;
     to.BcgovSerialnumber                     = from.SerialNumber;
     to.BcgovEncapsulatormaxcapacity          = from.EncapsulatorMaxCapacity;
     to.BcgovCustombuiltorkeypartserialnumber = from.CustomBuiltSerialNumber;
 }
        public async Task <IActionResult> UpdateEquipment([FromBody] ViewModels.Equipment item, string id)
        {
            if (!string.IsNullOrEmpty(id) && Guid.TryParse(id, out Guid equipmentId))
            {
                // get the Equipment
                MicrosoftDynamicsCRMbcgovEquipment equipment = _dynamicsClient.GetEquipmentByIdWithChildren(equipmentId);
                if (equipment == null)
                {
                    return(new NotFoundResult());
                }

                // get UserSettings from the session
                string       temp         = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
                UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(temp);

                // Get the current account
                var account = _dynamicsClient.GetAccountByIdWithChildren(Guid.Parse(userSettings.AccountId));

                MicrosoftDynamicsCRMbcgovEquipment patchEquipment = new MicrosoftDynamicsCRMbcgovEquipment();
                patchEquipment.CopyValues(item);

                try
                {
                    await _dynamicsClient.Equipments.UpdateAsync(equipmentId.ToString(), patchEquipment);
                }
                catch (OdataerrorException odee)
                {
                    _logger.LogError("Error updating Equipment");
                    _logger.LogError("Request:");
                    _logger.LogError(odee.Request.Content);
                    _logger.LogError("Response:");
                    _logger.LogError(odee.Response.Content);
                }

                equipment = _dynamicsClient.GetEquipmentByIdWithChildren(equipmentId);
                return(Json(equipment.ToViewModel()));
            }
            else
            {
                return(BadRequest());
            }
        }
        /// <summary>
        /// Convert a given Incident to an Application ViewModel
        /// </summary>
        public static ViewModels.Equipment ToViewModel(this MicrosoftDynamicsCRMbcgovEquipment equipment)
        {
            ViewModels.Equipment result = null;
            if (equipment != null)
            {
                result = new ViewModels.Equipment()
                {
                    Id                             = equipment.BcgovEquipmentid,
                    EquipmentType                  = (Equipmenttype?)equipment.BcgovEquipmenttype,
                    EquipmentTypeOther             = equipment.BcgovEquipmenttypeother,
                    Name                           = equipment.BcgovName,
                    PillpressEncapsulatorSize      = (Pillpressencapsulatorsize?)equipment.BcgovPillpressencapsulatorsize,
                    PillpressEncapsulatorSizeOther = equipment.BcgovPillpressencapsulatorsizeother,
                    LevelOfEquipmentAutomation     = (Levelofequipmentautomation?)equipment.BcgovLevelofautomation,
                    PillpressMaxCapacity           = equipment.BcgovPillpressmaxcapacity,
                    HowWasEquipmentBuilt           = (Howwasequipmentbuilt?)equipment.BcgovHowwasequipmentbuilt,
                    // HowWasEquipmentBuiltOther = equipment.BcgovHowwasequipmentbuiltother,
                    NameOfManufacturer      = equipment.BcgovNameofmanufacturer,
                    EquipmentMake           = equipment.BcgovMake,
                    EquipmentModel          = equipment.BcgovModel,
                    SerialNumber            = equipment.BcgovSerialnumber,
                    EncapsulatorMaxCapacity = equipment.BcgovEncapsulatormaxcapacity,
                    CustomBuiltSerialNumber = equipment.BcgovCustombuiltorkeypartserialnumber,
                };

                // business profile (account)
                if (equipment.BcgovCurrentBusinessOwner != null)
                {
                    result.BcgovCurrentBusinessOwner = equipment.BcgovCurrentBusinessOwner.ToViewModel();
                }

                // current location
                if (equipment.BcgovCurrentLocation != null)
                {
                    result.BcgovCurrentLocation = equipment.BcgovCurrentLocation.ToViewModel();
                }
            }
            return(result);
        }
 /// <summary>
 /// Add new entity to bcgov_equipments
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='body'>
 /// New entity
 /// </param>
 /// <param name='prefer'>
 /// Required in order for the service to return a JSON representation of the
 /// object.
 /// </param>
 public static MicrosoftDynamicsCRMbcgovEquipment Create(this IEquipments operations, MicrosoftDynamicsCRMbcgovEquipment body, string prefer = "return=representation")
 {
     return(operations.CreateAsync(body, prefer).GetAwaiter().GetResult());
 }
 /// <summary>
 /// Update entity in bcgov_equipments
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='bcgovEquipmentid'>
 /// key: bcgov_equipmentid of bcgov_equipment
 /// </param>
 /// <param name='body'>
 /// New property values
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task UpdateAsync(this IEquipments operations, string bcgovEquipmentid, MicrosoftDynamicsCRMbcgovEquipment body, CancellationToken cancellationToken = default(CancellationToken))
 {
     (await operations.UpdateWithHttpMessagesAsync(bcgovEquipmentid, body, null, cancellationToken).ConfigureAwait(false)).Dispose();
 }
 /// <summary>
 /// Update entity in bcgov_equipments
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='bcgovEquipmentid'>
 /// key: bcgov_equipmentid of bcgov_equipment
 /// </param>
 /// <param name='body'>
 /// New property values
 /// </param>
 public static void Update(this IEquipments operations, string bcgovEquipmentid, MicrosoftDynamicsCRMbcgovEquipment body)
 {
     operations.UpdateAsync(bcgovEquipmentid, body).GetAwaiter().GetResult();
 }
 /// <summary>
 /// Add new entity to bcgov_equipments
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='body'>
 /// New entity
 /// </param>
 /// <param name='prefer'>
 /// Required in order for the service to return a JSON representation of the
 /// object.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <MicrosoftDynamicsCRMbcgovEquipment> CreateAsync(this IEquipments operations, MicrosoftDynamicsCRMbcgovEquipment body, string prefer = "return=representation", CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.CreateWithHttpMessagesAsync(body, prefer, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
        /// <summary>
        /// Update entity in bcgov_equipments
        /// </summary>
        /// <param name='bcgovEquipmentid'>
        /// key: bcgov_equipmentid of bcgov_equipment
        /// </param>
        /// <param name='body'>
        /// New property values
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="HttpOperationException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse> UpdateWithHttpMessagesAsync(string bcgovEquipmentid, MicrosoftDynamicsCRMbcgovEquipment body, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (bcgovEquipmentid == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "bcgovEquipmentid");
            }
            if (body == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "body");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("bcgovEquipmentid", bcgovEquipmentid);
                tracingParameters.Add("body", body);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "bcgov_equipments({bcgov_equipmentid})").ToString();

            _url = _url.Replace("{bcgov_equipmentid}", System.Uri.EscapeDataString(bcgovEquipmentid));
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("PATCH");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            if (body != null)
            {
                _requestContent      = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 204)
            {
                var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                if (_httpResponse.Content != null)
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
                else
                {
                    _responseContent = string.Empty;
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Example #12
0
        /// <summary>
        /// Convert a given Incident to an Application ViewModel
        /// </summary>
        public static ViewModels.Equipment ToViewModel(this MicrosoftDynamicsCRMbcgovEquipment equipment)
        {
            string changeme = "changeme";

            ViewModels.Equipment result = null;
            if (equipment != null)
            {
                result = new ViewModels.Equipment()
                {
                    Id                                      = equipment.BcgovEquipmentid,
                    EquipmentType                           = changeme,
                    EquipmentTypeOther                      = changeme,
                    LevelOfEquipmentAutomation              = changeme,
                    PillpressEncapsulatorSize               = changeme,
                    PillpressEncapsulatorSizeOtherCheck     = changeme,
                    PillpressEncapsulatorSizeOther          = changeme,
                    PillpressMaxCapacity                    = changeme,
                    EncapsulatorMaxCapacity                 = changeme,
                    ExplanationOfEquipmentUse               = changeme,
                    HowWasEquipmentBuilt                    = changeme,
                    HowWasEquipmentBuiltOtherCheck          = changeme,
                    HowWasEquipmentBuiltOther               = changeme,
                    NameOfManufacturer                      = changeme,
                    EquipmentMake                           = changeme,
                    EquipmentModel                          = changeme,
                    SerialNumber                            = changeme,
                    HowEquipmentBuiltDescription            = changeme,
                    PersonBusinessThatBuiltEquipment        = changeme,
                    AddressPersonBusinessThatBuiltEquipment = changeme,
                    SerialNumberForCustomBuilt              = changeme,
                    CustomBuiltSerialNumber                 = changeme,
                    SerialNumberKeyPartDescription          = changeme,
                    OwnedBeforeJan2019                      = changeme,
                    PurchasedFromBcSeller                   = changeme,
                    PurchasedFromSellerOutsideofBc          = changeme,
                    ImportedToBcByAThirdParty               = changeme,
                    alternativeOwnershipArrangement         = changeme,
                    IAssembledItMyself                      = changeme,
                    HowCameIntoPossessionOtherCheck         = changeme,
                    HowCameIntoPossessionOther              = changeme,
                    NameOfBcSeller                          = changeme,
                    BCSellersAddress                        = changeme,
                    BcSellersContactPhoneNumber             = changeme,
                    BcSellersContactEmail                   = changeme,
                    Dateofpurchasefrombcseller              = changeme,
                    BcSellersRegistrationNumber             = changeme,
                    OutsideBcSellersName                    = changeme,
                    OutsideBCSellersAddress                 = changeme,
                    OutsideBcSellersLocation                = changeme,
                    DateOfPurchaseFromOutsideBcSeller       = changeme,
                    NameOfImporter                          = changeme,
                    ImportersAddress                        = changeme,
                    ImportersRegistrationNumber             = changeme,
                    nameoforiginatingseller                 = changeme,
                    OriginatingSellersAddress               = changeme,
                    OriginatingSellersLocation              = changeme,
                    DateOfPurchaseFromImporter              = changeme,
                    PossessUntilICanSell                    = changeme,
                    GiveNorLoanedToMe                       = changeme,
                    RentingOrLeasingFromAnotherBusiness     = changeme,
                    KindOfAlternateOwnershipOtherCheck      = changeme,
                    KindOfAlternateOwnershipOther           = changeme,
                    UsingToManufactureAProduct              = changeme,
                    AreYouARegisteredSeller                 = changeme,
                    NameOfBusinessThatHasGivenOrLoaned      = changeme,
                    AddressofBusinessthathasGivenorLoaned   = changeme,
                    PhoneOfBusinessThatHasGivenOrLoaned     = changeme,
                    EmailOfTheBusinessThatHasGivenOrLoaned  = changeme,
                    WhyAHaveYouAcceptedOrBorrowed           = changeme,
                    NameOfBusinessThatHasRentedOrLeased     = changeme,
                    AddressofBusinessThatHasRentedorLeased  = changeme,
                    PhoneOfBusinessThatHasRentedOrLeased    = changeme,
                    EmailOfBusinessThatHasRentedOrLeased    = changeme,
                    WhyHaveYouRentedOrLeased                = changeme,
                    WhenDidYouAssembleEquipment             = changeme,
                    WhereDidYouObtainParts                  = changeme,
                    DoYouAssembleForOtherBusinesses         = changeme,
                    DetailsOfAssemblyForOtherBusinesses     = changeme,
                    DetailsOfHowEquipmentCameIntoPossession = changeme,
                    DeclarationOfCorrectInformation         = changeme,
                    ConfirmationOfAuthorizedUse             = changeme,
                };
            }
            return(result);
        }
Example #13
0
 public static void CopyValues(this MicrosoftDynamicsCRMbcgovEquipment to, ViewModels.Equipment from)
 {
     // Equipment Information
 }