private async Task CallUrlBaiscAuth(string callBackUrl, string callBackCredentialDomain,
                                            string callbackCredentialUserName, string callbackCredentialPassword, TrashInspection trashInspection,
                                            bool inspectionApproved)
        {
            ChannelFactory <MicrotingWS_Port> factory;
            MicrotingWS_Port serviceProxy;
            BasicHttpBinding basicHttpBinding =
                new BasicHttpBinding();

            basicHttpBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
            basicHttpBinding.Security.Transport.ClientCredentialType =
                HttpClientCredentialType.Basic;
            factory =
                new ChannelFactory <MicrotingWS_Port>(basicHttpBinding,
                                                      new EndpointAddress(
                                                          new Uri(callBackUrl)));

            if (callBackCredentialDomain != "...")
            {
                factory.Credentials.Windows.ClientCredential.Domain = callBackCredentialDomain;
            }

            factory.Credentials.UserName.UserName = callbackCredentialUserName;
            factory.Credentials.UserName.Password = callbackCredentialPassword;

            serviceProxy = factory.CreateChannel();
            ((ICommunicationObject)serviceProxy).Open();

            try
            {
                WeighingFromMicroting2 weighingFromMicroting2 =
                    new WeighingFromMicroting2(trashInspection.WeighingNumber, inspectionApproved);
                Task <WeighingFromMicroting2_Result> result =
                    serviceProxy.WeighingFromMicroting2Async(weighingFromMicroting2);


                Console.WriteLine("[DBG] Result is " + result.Result.return_value);
                trashInspection.SuccessMessageFromCallBack = result.Result.return_value;
                trashInspection.ResponseSendToCallBackUrl  = true;
                await trashInspection.Update(_dbContext);
            }
            catch (Exception ex)
            {
                Console.WriteLine("[ERR] We got the following error: " + ex.Message);
                trashInspection.ErrorFromCallBack = ex.Message;
                await trashInspection.Update(_dbContext);
            }
            finally
            {
                // cleanup
                factory.Close();
                ((ICommunicationObject)serviceProxy).Close();
                // *** ENSURE CLEANUP *** \\
                //CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
                //OperationContext.Current = prevOpContext; // Or set to null if you didn't capture the previous context
            }
        }
#pragma warning disable 1998
        public async Task Handle(eFormRetrieved message)
        {
            Console.WriteLine("TrashInspection: We got a message : " + message.caseId);
            TrashInspectionCase trashInspectionCase = _dbContext.TrashInspectionCases.SingleOrDefault(x => x.SdkCaseId == message.caseId.ToString());

            if (trashInspectionCase != null)
            {
                Console.WriteLine("TrashInspection: The incoming case is a trash inspection related case");
                if (trashInspectionCase.Status < 77)
                {
                    trashInspectionCase.Status = 77;
                    await trashInspectionCase.Update(_dbContext);
                }

                TrashInspection trashInspection = _dbContext.TrashInspections.SingleOrDefault(x => x.Id == trashInspectionCase.TrashInspectionId);
                if (trashInspection != null)
                {
                    if (trashInspection.Status < 77)
                    {
                        trashInspection.Status = 77;
                        await trashInspection.Update(_dbContext);
                    }
                }
            }
        }
示例#3
0
        public async Task TrashInspectionModel_UpdateWFalse_DoesUpdate()
        {
            // Arrange
            Random rnd = new Random();

            TrashInspection trashInspection =
                new TrashInspection
            {
                CreatedAt          = DateTime.Now,
                Date               = DateTime.Now,
                EakCode            = rnd.Next(1, 255).ToString(),
                MustBeInspected    = false,
                Producer           = Guid.NewGuid().ToString(),
                RegistrationNumber = Guid.NewGuid().ToString(),
                Time               = DateTime.Now,
                Transporter        = Guid.NewGuid().ToString(),
                TrashFraction      = rnd.Next(1, 255).ToString(),
                WeighingNumber     = rnd.Next(1, 255).ToString()
            };
            await trashInspection.Create(DbContext);

            // Act
            trashInspection.CreatedAt          = trashInspection.CreatedAt;
            trashInspection.Date               = trashInspection.Date;
            trashInspection.EakCode            = trashInspection.EakCode;
            trashInspection.Id                 = trashInspection.Id;
            trashInspection.InstallationId     = trashInspection.InstallationId;
            trashInspection.MustBeInspected    = trashInspection.MustBeInspected;
            trashInspection.Producer           = trashInspection.Producer;
            trashInspection.RegistrationNumber = trashInspection.RegistrationNumber;
            trashInspection.Time               = trashInspection.Time;
            trashInspection.Transporter        = trashInspection.Transporter;
            trashInspection.TrashFraction      = trashInspection.TrashFraction;
            trashInspection.WeighingNumber     = trashInspection.WeighingNumber;

            await trashInspection.Update(DbContext);

            TrashInspection        dbTrashInspection   = DbContext.TrashInspections.AsNoTracking().First();
            List <TrashInspection> trashInspectionList = DbContext.TrashInspections.AsNoTracking().ToList();

            // Assert
            Assert.NotNull(dbTrashInspection);

            Assert.AreEqual(1, trashInspectionList.Count());

            Assert.AreEqual(trashInspection.CreatedAt.ToString(), dbTrashInspection.CreatedAt.ToString());
            Assert.AreEqual(trashInspection.Date.ToString(), dbTrashInspection.Date.ToString());
            Assert.AreEqual(trashInspection.EakCode, dbTrashInspection.EakCode);
            Assert.AreEqual(trashInspection.InstallationId, dbTrashInspection.InstallationId);
            Assert.AreEqual(trashInspection.MustBeInspected, dbTrashInspection.MustBeInspected);
            Assert.AreEqual(trashInspection.Producer, dbTrashInspection.Producer);
            Assert.AreEqual(trashInspection.RegistrationNumber, dbTrashInspection.RegistrationNumber);
            Assert.AreEqual(trashInspection.Time.ToString(), dbTrashInspection.Time.ToString());
            Assert.AreEqual(trashInspection.Transporter, dbTrashInspection.Transporter);
            Assert.AreEqual(trashInspection.TrashFraction, dbTrashInspection.TrashFraction);
            Assert.AreEqual(trashInspection.WeighingNumber, dbTrashInspection.WeighingNumber);
        }
        private async Task UpdateProducerAndTransporter(TrashInspection trashInspection, TrashInspectionModel createModel)
        {
            var producer = _dbContext.Producers
                           .Where(x => x.WorkflowState != Constants.WorkflowStates.Removed)
                           .SingleOrDefault(x => x.Name == createModel.Producer);

            if (producer == null)
            {
                producer = new Producer
                {
                    Name            = createModel.Producer,
                    Address         = createModel.ProducerAddress,
                    City            = createModel.ProducerCity,
                    ContactPerson   = createModel.ProducerContact,
                    Phone           = createModel.ProducerPhone,
                    ZipCode         = createModel.ProducerZip,
                    ForeignId       = createModel.ProducerForeignId,
                    UpdatedByUserId = _userService.UserId,
                    CreatedByUserId = _userService.UserId,
                };

                await producer.Create(_dbContext);
            }
            else
            {
                producer.Address         = createModel.ProducerAddress;
                producer.City            = createModel.ProducerCity;
                producer.ContactPerson   = createModel.ProducerContact;
                producer.Phone           = createModel.ProducerPhone;
                producer.ZipCode         = createModel.ProducerZip;
                producer.ForeignId       = createModel.ProducerForeignId;
                producer.UpdatedByUserId = _userService.UserId;
                await producer.Update(_dbContext);
            }

            trashInspection.ProducerId = producer.Id;

            var transporter = _dbContext.Transporters
                              .Where(x => x.WorkflowState != Constants.WorkflowStates.Removed)
                              .SingleOrDefault(x => x.Name == createModel.Transporter);

            if (transporter == null)
            {
                transporter = new Transporter
                {
                    Name            = createModel.Transporter,
                    Address         = createModel.TransporterAddress,
                    City            = createModel.TransporterCity,
                    ZipCode         = createModel.TransporterZip,
                    Phone           = createModel.TransporterPhone,
                    ContactPerson   = createModel.TransporterContact,
                    ForeignId       = createModel.TransporterForeignId,
                    UpdatedByUserId = _userService.UserId,
                    CreatedByUserId = _userService.UserId,
                };

                await transporter.Create(_dbContext);
            }
            else
            {
                transporter.Address         = createModel.TransporterAddress;
                transporter.City            = createModel.TransporterCity;
                transporter.ZipCode         = createModel.TransporterZip;
                transporter.Phone           = createModel.TransporterPhone;
                transporter.ContactPerson   = createModel.TransporterContact;
                transporter.ForeignId       = createModel.TransporterForeignId;
                transporter.UpdatedByUserId = _userService.UserId;
                await transporter.Update(_dbContext);
            }

            trashInspection.TransporterId = transporter.Id;
            transporter.UpdatedByUserId   = _userService.UserId;

            await trashInspection.Update(_dbContext);
        }
        public async Task <OperationResult> Create(TrashInspectionModel createModel)
        {
            var dateTime            = DateTime.UtcNow;
            var pluginConfiguration = await _dbContext.PluginConfigurationValues.SingleOrDefaultAsync(x => x.Name == "TrashInspectionBaseSettings:Token");

            if (pluginConfiguration == null)
            {
                return(new OperationResult(false));
            }

            if (createModel.Token == pluginConfiguration.Value && createModel.WeighingNumber != null)
            {
                try
                {
// Handling the situation, where incoming timestamp is not in UTC.
                    var utcAdjustment = await _dbContext.PluginConfigurationValues.SingleOrDefaultAsync(x => x.Name == "TrashInspectionBaseSettings:UtcAdjustment");

                    if (utcAdjustment.Value == "true")
                    {
                        if (createModel.Time.Hour > dateTime.Hour)
                        {
                            var timeSpan  = createModel.Time.Subtract(dateTime);
                            var minutes   = timeSpan.Hours * 60.0 + timeSpan.Minutes;
                            var hours     = minutes / 60.0;
                            var fullHours = Math.Round(hours);
                            createModel.Time = createModel.Time.AddHours(-fullHours);
                        }
                    }

                    TrashInspection trashInspection = await _dbContext.TrashInspections.FirstOrDefaultAsync(x =>
                                                                                                            x.WeighingNumber == createModel.WeighingNumber);

                    if (trashInspection != null)
                    {
                        return(new OperationResult(true, trashInspection.Id.ToString()));
                    }

                    trashInspection =
                        new TrashInspection
                    {
                        WeighingNumber     = createModel.WeighingNumber,
                        Date               = createModel.Date,
                        Time               = createModel.Time,
                        EakCode            = createModel.EakCode,
                        ExtendedInspection = createModel.ExtendedInspection,
                        RegistrationNumber = createModel.RegistrationNumber,
                        TrashFraction      = createModel.TrashFraction,
                        Producer           = createModel.Producer,
                        Transporter        = createModel.Transporter,
                        MustBeInspected    = createModel.MustBeInspected,
                        InspectionDone     = false,
                        Status             = 0,
                        UpdatedByUserId    = _userService.UserId,
                        CreatedByUserId    = _userService.UserId,
                    };

                    await trashInspection.Create(_dbContext);

                    var segment      = _dbContext.Segments.FirstOrDefault(x => x.Name == createModel.Segment);
                    var installation =
                        _dbContext.Installations.FirstOrDefault(x => x.Name == createModel.InstallationName);
                    var fraction =
                        _dbContext.Fractions.FirstOrDefault(x => x.ItemNumber == createModel.TrashFraction);

                    _coreHelper.LogEvent($"CreateTrashInspection: Segment: {createModel.Segment}, InstallationName: {createModel.InstallationName}, TrashFraction: {createModel.TrashFraction} ");
                    if (segment != null && installation != null && fraction != null)
                    {
                        trashInspection.SegmentId      = segment.Id;
                        trashInspection.FractionId     = fraction.Id;
                        trashInspection.InstallationId = installation.Id;
                        await trashInspection.Update(_dbContext);

                        createModel.SegmentId      = segment.Id;
                        createModel.FractionId     = fraction.Id;
                        createModel.InstallationId = installation.Id;
                        createModel.Id             = trashInspection.Id;

                        await UpdateProducerAndTransporter(trashInspection, createModel);

                        _coreHelper.LogEvent($"CreateTrashInspection: Segment: {segment.Name}, InstallationName: {installation.Name}, TrashFraction: {fraction.Name} ");
                        await _bus.SendLocal(new TrashInspectionReceived(createModel, fraction.Id, segment.Id, installation.Id));
                    }

                    return(new OperationResult(true, createModel.Id.ToString()));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return(new OperationResult(false));
                }
            }

            return(new OperationResult(false));
        }
        #pragma warning disable 1998
        public async Task Handle(eFormCompleted message)
        {
            Console.WriteLine("[DBG] TrashInspection: We got a message : " + message.caseId);
            TrashInspectionCase trashInspectionCase =
                _dbContext.TrashInspectionCases.SingleOrDefault(x => x.SdkCaseId == message.caseId.ToString());

            if (trashInspectionCase != null)
            {
                #region get case information

                CaseDto caseDto = await _sdkCore.CaseLookupMUId(message.caseId);

                await using MicrotingDbContext microtingDbContext = _sdkCore.DbContextHelper.GetDbContext();
                var      microtingUId      = caseDto.MicrotingUId;
                var      microtingCheckUId = caseDto.CheckUId;
                Language language          = await microtingDbContext.Languages.SingleAsync(x => x.Name == "Danish");

                ReplyElement theCase = await _sdkCore.CaseRead((int)microtingUId, (int)microtingCheckUId, language);

                CheckListValue dataElement        = (CheckListValue)theCase.ElementList[0];
                bool           inspectionApproved = false;
                string         approvedValue      = "";
                string         comment            = "";
                Console.WriteLine("[DBG] Trying to find the field with the approval value");
                foreach (var field in dataElement.DataItemList)
                {
                    Field f = (Field)field;
                    if (f.Label.Contains("Angiv om læs er Godkendt"))
                    {
                        Console.WriteLine($"The field is {f.Label}");
                        FieldValue fv         = f.FieldValues[0];
                        String     fieldValue = fv.Value;
                        inspectionApproved = (fieldValue == "1");
                        approvedValue      = fieldValue;
                        Console.WriteLine($"[DBG] We are setting the approved state to {inspectionApproved.ToString()}");
                    }

                    if (f.Label.Equals("Kommentar"))
                    {
                        Console.WriteLine($"[DBG] The field is {f.Label}");
                        FieldValue fv         = f.FieldValues[0];
                        String     fieldValue = fv.Value;
                        comment = fieldValue;
                        Console.WriteLine($"[DBG] We are setting the comment to {comment.ToString()}");
                    }
                }
                #endregion

                Console.WriteLine("TrashInspection: The incoming case is a trash inspection related case");
                trashInspectionCase.Status = 100;
                await trashInspectionCase.Update(_dbContext);

                TrashInspection trashInspection =
                    _dbContext.TrashInspections.SingleOrDefault(x => x.Id == trashInspectionCase.TrashInspectionId);
                if (trashInspection != null)
                {
                    trashInspection.Status         = 100;
                    trashInspection.IsApproved     = inspectionApproved;
                    trashInspection.Comment        = comment;
                    trashInspection.ApprovedValue  = approvedValue;
                    trashInspection.InspectionDone = true;
                    await trashInspection.Update(_dbContext);

                    List <TrashInspectionCase> trashInspectionCases = _dbContext.TrashInspectionCases
                                                                      .Where(x => x.TrashInspectionId == trashInspection.Id).ToList();
                    foreach (TrashInspectionCase inspectionCase in trashInspectionCases)
                    {
                        if (await _sdkCore.CaseDelete(int.Parse(inspectionCase.SdkCaseId)))
                        {
                            inspectionCase.WorkflowState = Constants.WorkflowStates.Retracted;
                            await inspectionCase.Update(_dbContext);
                        }
                    }

                    #region get settings

                    string callBackUrl = _dbContext.PluginConfigurationValues
                                         .SingleOrDefault(x => x.Name == "TrashInspectionBaseSettings:callBackUrl")?.Value;
                    Console.WriteLine("[DBG] callBackUrl is : " + callBackUrl);

                    string callBackCredentialDomain = _dbContext.PluginConfigurationValues.SingleOrDefault(x =>
                                                                                                           x.Name == "TrashInspectionBaseSettings:CallBackCredentialDomain")?.Value;
                    Console.WriteLine("[DBG] callBackCredentialDomain is : " + callBackCredentialDomain);

                    string callbackCredentialUserName = _dbContext.PluginConfigurationValues.SingleOrDefault(x =>
                                                                                                             x.Name == "TrashInspectionBaseSettings:callbackCredentialUserName")?.Value;
                    Console.WriteLine("[DBG] callbackCredentialUserName is : " + callbackCredentialUserName);

                    string callbackCredentialPassword = _dbContext.PluginConfigurationValues.SingleOrDefault(x =>
                                                                                                             x.Name == "TrashInspectionBaseSettings:CallbackCredentialPassword")?.Value;
                    Console.WriteLine("[DBG] callbackCredentialPassword is : " + callbackCredentialPassword);

                    string callbackCredentialAuthType = _dbContext.PluginConfigurationValues.SingleOrDefault(x =>
                                                                                                             x.Name == "TrashInspectionBaseSettings:CallbackCredentialAuthType")?.Value;
                    Console.WriteLine("[DBG] callbackCredentialAuthType is : " + callbackCredentialAuthType);

                    Console.WriteLine($"[DBG] trashInspection.WeighingNumber is {trashInspection.WeighingNumber}");
                    #endregion

                    switch (callbackCredentialAuthType)
                    {
                    case "NTLM":
                        await CallUrlNtlmAuth(callBackUrl, callBackCredentialDomain, callbackCredentialUserName,
                                              callbackCredentialPassword, trashInspection, inspectionApproved);

                        break;

                    case "basic":
                    default:
                        await CallUrlBaiscAuth(callBackUrl, callBackCredentialDomain, callbackCredentialUserName,
                                               callbackCredentialPassword, trashInspection, inspectionApproved);

                        break;
                    }
                }
            }
        }