Exemplo n.º 1
0
 public static List<TestRecommendation> BuildSickListFromDataBaseData(string idDispensaryStage1)
 {
     List<TestRecommendation> llr = new List<TestRecommendation>();
     if (idDispensaryStage1 != "")
     {
         using (SqlConnection connection = Global.GetSqlConnection())
         {
             string findR = "SELECT * FROM Recommendation WHERE idDispensaryStage1 = '" + idDispensaryStage1 + "'";
             SqlCommand Rcommand = new SqlCommand(findR, connection);
             using (SqlDataReader RReader = Rcommand.ExecuteReader())
             {
                 while (RReader.Read())
                 {
                     Recommendation r = new Recommendation();
                     if (RReader["Text"].ToString() != "")
                         r.Text = RReader["Text"].ToString();
                     if (RReader["Date"].ToString() != "")
                         r.Date = Convert.ToDateTime(RReader["Date"]);
                     TestRecommendation tr = new TestRecommendation(r);
                     if (RReader["IdDoctor"].ToString() != "")
                         tr.doctor = TestDoctor.BuildTestDoctorFromDataBase(RReader["IdDoctor"].ToString());
                     llr.Add(tr);
                 }
             }
         }
     }
     if (llr.Count != 0)
         return llr;
     else
         return null;
 }
Exemplo n.º 2
0
 public void Detach(Recommendation recommendation)
 {
     this.RunInTransaction(session =>
     {
         session.Delete(recommendation);
     });
 }
Exemplo n.º 3
0
 public TestRecommendation(Recommendation r, string idLpu = "")
 {
     if (r != null)
     {
         recommendation = r;
         doctor = new TestDoctor(r.Doctor, idLpu);
     }
 }
        public async Task GetRecommendationAsync()
        {
            Mock <RecommendationService.RecommendationServiceClient> mockGrpcClient = new Mock <RecommendationService.RecommendationServiceClient>(MockBehavior.Strict);
            GetRecommendationRequest expectedRequest = new GetRecommendationRequest
            {
                ResourceName = new RecommendationName("[CUSTOMER]", "[RECOMMENDATION]").ToString(),
            };
            Recommendation expectedResponse = new Recommendation
            {
                ResourceName = "resourceName2625949903",
            };

            mockGrpcClient.Setup(x => x.GetRecommendationAsync(expectedRequest, It.IsAny <CallOptions>()))
            .Returns(new Grpc.Core.AsyncUnaryCall <Recommendation>(Task.FromResult(expectedResponse), null, null, null, null));
            RecommendationServiceClient client   = new RecommendationServiceClientImpl(mockGrpcClient.Object, null);
            string         formattedResourceName = new RecommendationName("[CUSTOMER]", "[RECOMMENDATION]").ToString();
            Recommendation response = await client.GetRecommendationAsync(formattedResourceName);

            Assert.AreEqual(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }
        public string Build(CloudApplication cloudApplication, Recommendation recommendation, OrchestratorSession session)
        {
            var projectPath = new FileInfo(recommendation.ProjectPath).Directory?.FullName;

            if (string.IsNullOrEmpty(projectPath))
            {
                throw new InvalidProjectPathException("The project path provided is invalid.");
            }

            // General Settings
            var appSettingsContainer = new RecipeProps <Dictionary <string, object> >(
                cloudApplication.StackName,
                projectPath,
                recommendation.Recipe.Id,
                recommendation.Recipe.Version,
                session.AWSAccountId,
                session.AWSRegion,
                new ()
                )
            {
                ECRRepositoryName            = recommendation.DeploymentBundle.ECRRepositoryName ?? "",
                ECRImageTag                  = recommendation.DeploymentBundle.ECRImageTag ?? "",
                DotnetPublishZipPath         = recommendation.DeploymentBundle.DotnetPublishZipPath ?? "",
                DotnetPublishOutputDirectory = recommendation.DeploymentBundle.DotnetPublishOutputDirectory ?? ""
            };

            // Option Settings
            foreach (var optionSetting in recommendation.Recipe.OptionSettings)
            {
                var optionSettingValue = recommendation.GetOptionSettingValue(optionSetting);

                if (optionSettingValue != null)
                {
                    appSettingsContainer.Settings[optionSetting.Id] = optionSettingValue;
                }
            }

            return(JsonConvert.SerializeObject(appSettingsContainer, Formatting.Indented));
        }
    }
Exemplo n.º 6
0
        public List <Recommendation> GetRecommendatinsBySerieId(int serieid)
        {
            List <Recommendation> recommendations = new List <Recommendation>();
            string query = "SELECT * FROM Recommendation WHERE serieid1 = @serieid";

            using (var conn = new SqlConnection(ConnectionString))
            {
                conn.Open();
                using (var cmd = new SqlCommand(query, conn))
                {
                    cmd.Parameters.Add(new SqlParameter("@serieid", serieid));
                    using (var reader = cmd.ExecuteReader())
                    {
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                Recommendation recommendation = new Recommendation
                                {
                                    Id          = (int)reader["id"],
                                    Name        = (string)reader["name"],
                                    Description = (string)reader["description"],
                                    Userid      = (int)reader["userid"],
                                    Serie1      = new Serie
                                    {
                                        Id = (int)reader["serieid1"],
                                    },
                                    Serie2 = new Serie
                                    {
                                        Id = (int)reader["serieid2"],
                                    }
                                };
                                recommendations.Add(recommendation);
                            }
                        }
                    }
                }
                return(recommendations);
            }
        }
        public void Recommendation_PropertySetToNull_ShouldSetBackingVariableAndPreserveTotalPrice()
        {
            var hddPrice = 200.00M;
            var sut      = new Recommendation();

            Assert.IsNull(sut.HardDiskDrive);
            Assert.IsNull(sut.Processor);
            Assert.AreEqual(0.00M, sut.TotalPrice);

            sut.HardDiskDrive = new Component {
                Category = ComponentType.HardDrive, Price = hddPrice
            };

            Assert.IsNotNull(sut.HardDiskDrive);
            Assert.AreEqual(hddPrice, sut.TotalPrice);

            sut.Processor = null;

            Assert.IsNull(sut.Processor);
            Assert.IsNotNull(sut.HardDiskDrive);
            Assert.AreEqual(hddPrice, sut.TotalPrice);
        }
Exemplo n.º 8
0
        public static EditRecommendationViewModel ToEditRecommendationViewModel(Recommendation rec)
        {
            if (rec == null)
            {
                return(null);
            }

            EditRecommendationViewModel vm = new EditRecommendationViewModel();

            vm.Id                 = rec.Id;
            vm.CompanyName        = rec.CompanyName;
            vm.CompanyUrl         = rec.CompanyUrl;
            vm.CssClass           = rec.CssClass;
            vm.FirstName          = rec.FirstName;
            vm.LastName           = rec.LastName;
            vm.LinkedIn           = rec.LinkedIn;
            vm.Message            = rec.Message;
            vm.PositionTitle      = rec.PositionTitle;
            vm.RecommendationDate = rec.RecommendationDate;

            return(vm);
        }
Exemplo n.º 9
0
        public static Recommendation From(EditRecommendationViewModel vm)
        {
            if (vm == null)
            {
                return(null);
            }

            Recommendation rec = new Recommendation();

            rec.Id                 = vm.Id;
            rec.CompanyName        = vm.CompanyName;
            rec.CompanyUrl         = vm.CompanyUrl;
            rec.CssClass           = vm.CssClass;
            rec.FirstName          = vm.FirstName;
            rec.LastName           = vm.LastName;
            rec.LinkedIn           = vm.LinkedIn;
            rec.Message            = vm.Message;
            rec.PositionTitle      = vm.PositionTitle;
            rec.RecommendationDate = vm.RecommendationDate;

            return(rec);
        }
        public async Task <object> Execute(Recommendation recommendation, OptionSettingItem optionSetting)
        {
            var applications = await _awsResourceQueryer.ListOfElasticBeanstalkApplications();

            var currentTypeHintResponse = recommendation.GetOptionSettingValue <BeanstalkApplicationTypeHintResponse>(optionSetting);

            var userInputConfiguration = new UserInputConfiguration <ApplicationDescription>(
                app => app.ApplicationName,
                app => app.ApplicationName.Equals(currentTypeHintResponse?.ApplicationName),
                currentTypeHintResponse.ApplicationName)
            {
                AskNewName = true,
            };

            var userResponse = _consoleUtilities.AskUserToChooseOrCreateNew(applications, "Select Elastic Beanstalk application to deploy to:", userInputConfiguration);

            return(new BeanstalkApplicationTypeHintResponse(
                       userResponse.CreateNew,
                       userResponse.SelectedOption?.ApplicationName ?? userResponse.NewName
                       ?? throw new UserPromptForNameReturnedNullException("The user response for a new application name was null.")
                       ));
        }
        public async Task <object> Execute(Recommendation recommendation, OptionSettingItem optionSetting)
        {
            var applications = await _awsResourceQueryer.ListOfElasticBeanstalkApplications(_session);

            var currentTypeHintResponse = recommendation.GetOptionSettingValue <BeanstalkApplicationTypeHintResponse>(optionSetting);

            var userInputConfiguration = new UserInputConfiguration <ApplicationDescription>
            {
                DisplaySelector = app => app.ApplicationName,
                DefaultSelector = app => app.ApplicationName.Equals(currentTypeHintResponse?.ApplicationName),
                AskNewName      = true,
                DefaultNewName  = currentTypeHintResponse.ApplicationName
            };

            var userResponse = _consoleUtilities.AskUserToChooseOrCreateNew(applications, "Select Elastic Beanstalk application to deploy to:", userInputConfiguration);

            return(new BeanstalkApplicationTypeHintResponse
            {
                CreateNew = userResponse.CreateNew,
                ApplicationName = userResponse.SelectedOption?.ApplicationName ?? userResponse.NewName
            });
        }
Exemplo n.º 12
0
        public SetOptionSettingTests()
        {
            var projectPath = SystemIOUtilities.ResolvePath("WebAppNoDockerFile");

            var parser         = new ProjectDefinitionParser(new FileManager(), new DirectoryManager());
            var awsCredentials = new Mock <AWSCredentials>();
            var session        = new OrchestratorSession(
                parser.Parse(projectPath).Result,
                awsCredentials.Object,
                "us-west-2",
                "123456789012")
            {
                AWSProfileName = "default"
            };

            var engine          = new RecommendationEngine(new[] { RecipeLocator.FindRecipeDefinitionsPath() }, session);
            var recommendations = engine.ComputeRecommendations().GetAwaiter().GetResult();

            _recommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_RECIPE_ID);

            _optionSetting = _recommendation.Recipe.OptionSettings.First(x => x.Id.Equals("EnvironmentType"));
        }
Exemplo n.º 13
0
        public ActionResult CreateRecommendation(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here


                string   recommendation  = collection["recommendation"].ToString();
                int      committee_id    = int.Parse(collection["Committees"].ToString());
                DateTime recdeadlinedate = DateTime.Parse(collection["recdeadlinedate"].ToString());
                DateTime recdate         = DateTime.Parse(collection["recdate"].ToString());

                int PActionID = int.Parse(collection["SourceID"].ToString());

                IRecommendationsRepository recs    = new RecommendationsRepository();
                IGenericRepository         generic = new GenericRepository();
                Recommendation             r       = new Recommendation();

                r.AddedDate         = DateTime.Now;
                r.CommitteeID       = committee_id;
                r.DeadlineDate      = recdeadlinedate;
                r.RecDate           = recdate;
                r.RecommendationX   = recommendation;
                r.ParagraphActionID = PActionID;

                int i = recs.SaveRec(r);

                ViewData["Committees"]      = new SelectList(generic.getAllCommitteesSelect(), "ID", "Description");
                ViewData["recommendations"] = recs.getAllRecommendationsByParagraph(PActionID);
                ViewData["PActionID"]       = PActionID;
                return(PartialView("Recommendations"));

                //return RedirectToAction("Index");
            }
            catch
            {
                return(View());
            }
        }
Exemplo n.º 14
0
        public async Task CreateDotnetPublishZip_NotSelfContained()
        {
            var projectPath       = SystemIOUtilities.ResolvePath("ConsoleAppTask");
            var projectDefinition = new ProjectDefinition(projectPath);
            var recipeDefinition  = new Mock <RecipeDefinition>();
            var recommendation    = new Recommendation(recipeDefinition.Object, projectDefinition.ProjectPath, 100, new Dictionary <string, string>());

            recommendation.DeploymentBundle.DotnetPublishSelfContainedBuild       = false;
            recommendation.DeploymentBundle.DotnetPublishBuildConfiguration       = "Release";
            recommendation.DeploymentBundle.DotnetPublishAdditionalBuildArguments = "--nologo";

            await _deploymentBundleHandler.CreateDotnetPublishZip(recommendation);

            var expectedCommand =
                $"dotnet publish \"{projectDefinition.ProjectPath}\"" +
                $" -o \"{_directoryManager.CreatedDirectories.First()}\"" +
                " -c Release" +
                " " +
                " --nologo";

            Assert.Equal(expectedCommand, _commandLineWrapper.CommandsToExecute.First().Command);
        }
Exemplo n.º 15
0
        public async Task <object> Execute(Recommendation recommendation, OptionSettingItem optionSetting)
        {
            var currentVpcTypeHintResponse = optionSetting.GetTypeHintData <VpcTypeHintResponse>();

            var vpcs = await _awsResourceQueryer.GetListOfVpcs();

            var userInputConfig = new UserInputConfiguration <Vpc>(
                vpc =>
            {
                var name     = vpc.Tags?.FirstOrDefault(x => x.Key == "Name")?.Value ?? string.Empty;
                var namePart =
                    string.IsNullOrEmpty(name)
                            ? ""
                            : $" ({name}) ";

                var isDefaultPart =
                    vpc.IsDefault
                            ? " *** Account Default VPC ***"
                            : "";

                return($"{vpc.VpcId}{namePart}{isDefaultPart}");
            },
                vpc =>
                !string.IsNullOrEmpty(currentVpcTypeHintResponse?.VpcId)
                        ? vpc.VpcId == currentVpcTypeHintResponse.VpcId
                        : vpc.IsDefault);

            var userResponse = _consoleUtilities.AskUserToChooseOrCreateNew(
                vpcs,
                "Select a VPC",
                userInputConfig);

            return(new VpcTypeHintResponse(
                       userResponse.SelectedOption?.IsDefault == true,
                       userResponse.CreateNew,
                       userResponse.SelectedOption?.VpcId ?? ""
                       ));
        }
Exemplo n.º 16
0
        public ActionResult CreateRecommendation(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                string recommendation = collection["recommendation"].ToString();
                int committee_id = int.Parse(collection["Committees"].ToString());
                DateTime recdeadlinedate = DateTime.Parse(collection["recdeadlinedate"].ToString());
                DateTime recdate = DateTime.Parse(collection["recdate"].ToString());

                int PActionID = int.Parse(collection["SourceID"].ToString());

                IRecommendationsRepository recs = new RecommendationsRepository();
                IGenericRepository generic = new GenericRepository();
                Recommendation r = new Recommendation();

                r.AddedDate = DateTime.Now;
                r.CommitteeID = committee_id;
                r.DeadlineDate = recdeadlinedate;
                r.RecDate = recdate;
                r.RecommendationX = recommendation;
                r.ParagraphActionID = PActionID;

                int i= recs.SaveRec(r);

                ViewData["Committees"] = new SelectList(generic.getAllCommitteesSelect(), "ID", "Description");
                ViewData["recommendations"] = recs.getAllRecommendationsByParagraph(PActionID);
                ViewData["PActionID"] = PActionID;
                return PartialView("Recommendations");

                //return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
Exemplo n.º 17
0
        // Construye XML con las recomendaciones para un cliente
        public static string xmlRecommendationBuilder(Recommendation rec)
        {
            string xml = header + "\n<Recommendations>\n";

            xml += "\t<Opening>" + rec.Opening + "</Opening>\n";
            xml += "\t<Products>\n";
            xml += "\t\t<Usually>\n";
            foreach (RecProduct product in rec.Usually)
            {
                xml += "\t\t\t<UCategory name=\"" + product.Category + "\">\n";
                xml += "\t\t\t\t<UProduct>" + product.Name + "</UProduct>\n";
                xml += "\t\t\t\t<UTimes>" + product.Times + "</UTimes>\n";
                xml += "\t\t\t</UCategory>\n";
            }
            xml += "\t\t</Usually>\n";
            xml += "\t\t<Promotional>\n";
            foreach (RecProduct product in rec.Promotional)
            {
                xml += "\t\t\t<PProduct name=\"" + product.Name + "\">\n";
                xml += "\t\t\t\t<PDiscount>" + Convert.ToString(product.Discount).Replace(',', '.')
                       + "</PDiscount>\n";
                xml += "\t\t\t\t<PUnits>" + Convert.ToString(product.DiscountedUnit).Replace(',', '.')
                       + "</PUnits>\n";
                xml += "\t\t\t</PProduct>\n";
            }
            xml += "\t\t</Promotional>\n";
            xml += "\t\t<Recommended>\n";
            foreach (RecProduct product in rec.Recommended)
            {
                xml += "\t\t\t<RProduct name=\"" + product.Name + "\">\n";
                xml += "\t\t\t\t<RCategory>" + product.Category + "</RCategory>\n";
                xml += "\t\t\t</RProduct>\n";
            }
            xml += "\t\t</Recommended>\n";
            xml += "\t</Products>\n";
            xml += "</Recommendations>";
            return(xml);
        }
Exemplo n.º 18
0
    public void RecommendHighValueShip()
    {
        while (recommendationProvided < 3)
        {
            double         highestValue    = 0;
            ShipController shipToRecommend = null;
            foreach (ShipController ship in priorityQueue.queue)
            {
                if (!isShipInConsideration(ship))
                {
                    continue;
                }

                if (ship.Ship.cargo * ship.Ship.value > highestValue)
                {
                    highestValue    = ship.Ship.cargo * ship.Ship.value;
                    shipToRecommend = ship;
                }
            }

            if (shipToRecommend != null)
            {
                Recommendation recommendation = new Recommendation();
                recommendation.ship            = shipToRecommend;
                recommendation.desiredPriority = 3;
                if (showJustifiction)
                {
                    recommendation.justification = "Because this ship has very high cargo value.";
                }

                ProvideRecommendation(recommendation);
            }
            else
            {
                break;
            }
        }
    }
Exemplo n.º 19
0
        public async stt::Task MarkRecommendationFailedAsync_ResourceNames()
        {
            moq::Mock <Recommender.RecommenderClient> mockGrpcClient = new moq::Mock <Recommender.RecommenderClient>(moq::MockBehavior.Strict);
            MarkRecommendationFailedRequest           request        = new MarkRecommendationFailedRequest
            {
                RecommendationName = new RecommendationName("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
                StateMetadata      =
                {
                    {
                        "key8a0b6e3c",
                        "value60c16320"
                    },
                },
                Etag = "etage8ad7218",
            };
            Recommendation expectedResponse = new Recommendation
            {
                RecommendationName = new RecommendationName("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
                Description        = "description2cf9da67",
                LastRefreshTime    = new wkt::Timestamp(),
                PrimaryImpact      = new Impact(),
                AdditionalImpact   = { new Impact(), },
                Content            = new RecommendationContent(),
                StateInfo          = new RecommendationStateInfo(),
                Etag = "etage8ad7218",
                RecommenderSubtype = "recommender_subtype6a5b10f9",
            };

            mockGrpcClient.Setup(x => x.MarkRecommendationFailedAsync(request, moq::It.IsAny <grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall <Recommendation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
            RecommenderClient client = new RecommenderClientImpl(mockGrpcClient.Object, null);
            Recommendation    responseCallSettings = await client.MarkRecommendationFailedAsync(request.RecommendationName, request.StateMetadata, request.Etag, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));

            xunit::Assert.Same(expectedResponse, responseCallSettings);
            Recommendation responseCancellationToken = await client.MarkRecommendationFailedAsync(request.RecommendationName, request.StateMetadata, request.Etag, st::CancellationToken.None);

            xunit::Assert.Same(expectedResponse, responseCancellationToken);
            mockGrpcClient.VerifyAll();
        }
Exemplo n.º 20
0
        public void RegisterRecommendationTest()
        {
            Recommendation recommendation3 = new Recommendation
            {
                RecommendationId = 3,
                UsuarioId        = 2,
                SupplierId       = 2,
                Note             = "Esta bien",
                Mark             = 10
            };


            mockRepository.Setup(x => x.RegisterRecommendation(recommendation3))
            .Returns(true);

            var handler = new RegisterRecommendationHandler(mockRepository.Object);

            RegisterRecommendation re = new RegisterRecommendation(recommendation3);

            var res = handler.Handle(re, ct);

            Assert.IsTrue(res.Result);
        }
        public async Task <object> Execute(Recommendation recommendation, OptionSettingItem optionSetting)
        {
            var clusters = await _awsResourceQueryer.ListOfECSClusters(_session);

            var currentTypeHintResponse = recommendation.GetOptionSettingValue <ECSClusterTypeHintResponse>(optionSetting);

            var userInputConfiguration = new UserInputConfiguration <Cluster>
            {
                DisplaySelector = cluster => cluster.ClusterName,
                DefaultSelector = cluster => cluster.ClusterArn.Equals(currentTypeHintResponse?.ClusterArn),
                AskNewName      = true,
                DefaultNewName  = currentTypeHintResponse.NewClusterName
            };

            var userResponse = _consoleUtilities.AskUserToChooseOrCreateNew(clusters, "Select ECS cluster to deploy to:", userInputConfiguration);

            return(new ECSClusterTypeHintResponse
            {
                CreateNew = userResponse.CreateNew,
                ClusterArn = userResponse.SelectedOption?.ClusterArn ?? string.Empty,
                NewClusterName = userResponse.NewName
            });
        }
        public async Task DeployRecommendation(CloudApplication cloudApplication, Recommendation recommendation)
        {
            _interactiveService.LogMessageLine(string.Empty);
            _interactiveService.LogMessageLine($"Initiating deployment: {recommendation.Name}");

            if (recommendation.Recipe.DeploymentType == DeploymentTypes.CdkProject)
            {
                _interactiveService.LogMessageLine("AWS CDK is being configured.");
                await _session.CdkManager.EnsureCompatibleCDKExists(CDKConstants.DeployToolWorkspaceDirectoryRoot, CDKConstants.MinimumCDKVersion);
            }

            switch (recommendation.Recipe.DeploymentType)
            {
            case DeploymentTypes.CdkProject:
                await _cdkProjectHandler.CreateCdkDeployment(_session, cloudApplication, recommendation);

                break;

            default:
                _interactiveService.LogErrorMessageLine($"Unknown deployment type {recommendation.Recipe.DeploymentType} specified in recipe.");
                break;
            }
        }
        public ICollection <Recommendation> ReadAll()
        {
            var           recommendations = new List <Recommendation>();
            SqlCommand    command         = new SqlCommand("select * from Recommendation", _conn);
            SqlDataReader reader          = command.ExecuteReader();

            while (reader.Read())
            {
                int    id              = (int)reader["id"];
                int    rating          = (int)reader["Rating"];
                string narrative       = reader["Narrative"].ToString();
                string recommenderName = reader["recommenderName"].ToString();
                var    recommendation  = new Recommendation
                {
                    Id              = id,
                    Rating          = rating,
                    Narrative       = narrative,
                    RecommenderName = recommenderName
                };
                recommendations.Add(recommendation);
            }
            return(recommendations);
        }
        public Recommendation Read(int id)
        {
            Recommendation recommendation = null;
            SqlCommand     command        = new SqlCommand("select * from Recommendation where Id = @id", _conn);

            command.Parameters.Add(new SqlParameter("id", id));
            SqlDataReader reader = command.ExecuteReader();

            if (reader.Read())
            {
                int    rating          = (int)reader["Rating"];
                string narrative       = reader["Narrative"].ToString();
                string recommenderName = reader["RecommenderName"].ToString();
                recommendation = new Recommendation
                {
                    Id              = id,
                    Rating          = rating,
                    Narrative       = narrative,
                    RecommenderName = recommenderName
                };
            }
            return(recommendation);
        }
Exemplo n.º 25
0
        public async Task GetProductRecommendationByIdAsync_ShouldReturnRecommendationsForProduct()
        {
            var productId = "12417832";
            var OfferType = "ONLINE_AND_STORE";


            var recommendations = new Recommendation[] { new Recommendation {
                                                             ProductId = productId, OfferType = "ONLINE_AND_STORE"
                                                         } };

            var mock = new Mock <IRepositoryRest>();

            mock.Setup(m => m.GetRecommendationsByProeuctIddAsync(productId)).Returns(Task.FromResult(recommendations.ToList()));

            var productService = new ProductService(mock.Object);

            var result = await productService.GetProductRecommendationByIdAsync(productId);

            Assert.IsTrue(result != null, "Should not return null");
            Assert.IsTrue(result.Count > 0, "Should return at least one recommendation");
            Assert.AreEqual(result[0].OfferType, OfferType);
            Assert.AreEqual(result[0].ProductId, productId);
        }
        public async Task CreateDotnetPublishZip_SelfContained()
        {
            var projectPath = SystemIOUtilities.ResolvePath("ConsoleAppTask");
            var project     = await _projectDefinitionParser.Parse(projectPath);

            var recommendation = new Recommendation(_recipeDefinition, project, new List <OptionSettingItem>(), 100, new Dictionary <string, string>());

            recommendation.DeploymentBundle.DotnetPublishSelfContainedBuild       = true;
            recommendation.DeploymentBundle.DotnetPublishBuildConfiguration       = "Release";
            recommendation.DeploymentBundle.DotnetPublishAdditionalBuildArguments = "--nologo";

            await _deploymentBundleHandler.CreateDotnetPublishZip(recommendation);

            var expectedCommand =
                $"dotnet publish \"{project.ProjectPath}\"" +
                $" -o \"{_directoryManager.CreatedDirectories.First()}\"" +
                " -c Release" +
                " --runtime linux-x64" +
                " --nologo" +
                " --self-contained true";

            Assert.Equal(expectedCommand, _commandLineWrapper.CommandsToExecute.First().Command);
        }
        public static List <Item> AssociationRecommendationByUser(int userId, int take)
        {
            List <Item> items = new List <Item>();

            List <string> itemIds = new List <string>();

            //TODO #3

            //get 20 log events for the user.
            List <CollectorLog> logs = GetUserLogs(userId, 20);

            if (logs.Count == 0)
            {
                return(items);
            }

            List <Rule> rules = GetSeededRules(logs);

            //get the pre-seeded objects based on confidence
            List <Recommendation> recs = new List <Recommendation>();

            //for each rule returned, evaluate the confidence
            foreach (Rule r in rules)
            {
                Recommendation rec = new Recommendation();
                rec.id         = int.Parse(r.target);
                rec.confidence = r.confidence;
                recs.Add(rec);

                itemIds.Add(rec.id.ToString());
            }

            items = GetItemsByImdbIds(itemIds);

            //return the "take" number of records
            return(items.Take(take).ToList());
        }
Exemplo n.º 28
0
        public Collection <Recommendation> GetRecommendations(double userId, double[] userIds)
        {
            var model = new Collection <Recommendation>();
            var str   = string.Join(",", userIds.Take(15000));

            var query = string.Format(
                @"select top 25 movie_id, m.title, AVG(rating) as avgrating, COUNT(rating) as [count]
  from ratings
  inner join movies as m
  on movie_id = m.id
where  [user_id] in ({0})
 and movie_id not in (select movie_id from ratings where [user_id] = @userId and rating >= 3)
group by movie_id, title
order by avgrating desc", str);

            this.Connection.Open();

            var command = new SqlCommand(query, this.Connection);

            command.Parameters.Add(new SqlParameter("@userId", userId));
            command.CommandTimeout = 600;

            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    var r = new Recommendation();
                    r.MovieTitle = (string)reader["title"];
                    r.MovieId    = (Int64)reader["movie_id"];
                    r.Stars      = (decimal)reader["avgrating"];
                    r.Count      = (int)reader["count"];
                    model.Add(r);
                }
            }

            return(model);
        }
Exemplo n.º 29
0
        /// <summary>
        /// Checks if the system meets all the necessary requirements for deployment.
        /// </summary>
        public async Task <List <SystemCapability> > EvaluateSystemCapabilities(Recommendation selectedRecommendation)
        {
            var capabilities       = new List <SystemCapability>();
            var systemCapabilities = await Evaluate();

            if (selectedRecommendation.Recipe.DeploymentType == DeploymentTypes.CdkProject &&
                !systemCapabilities.NodeJsMinVersionInstalled)
            {
                capabilities.Add(new SystemCapability("NodeJS", false, false)
                {
                    InstallationUrl = "https://nodejs.org/en/download/",
                    Message         = "The selected deployment uses the AWS CDK, which requires version of Node.js higher than your current installation. The latest LTS version of Node.js is recommended and can be installed from https://nodejs.org/en/download/. Specifically, AWS CDK requires 10.3+ to work properly."
                });
            }

            if (selectedRecommendation.Recipe.DeploymentBundle == DeploymentBundleTypes.Container)
            {
                if (!systemCapabilities.DockerInfo.DockerInstalled)
                {
                    capabilities.Add(new SystemCapability("Docker", false, false)
                    {
                        InstallationUrl = "https://docs.docker.com/engine/install/",
                        Message         = "The selected deployment option requires Docker, which was not detected. Please install and start the appropriate version of Docker for you OS: https://docs.docker.com/engine/install/"
                    });
                }
                else if (!systemCapabilities.DockerInfo.DockerContainerType.Equals("linux", StringComparison.OrdinalIgnoreCase))
                {
                    capabilities.Add(new SystemCapability("Docker", true, false)
                    {
                        Message = "The deployment tool requires Docker to be running in linux mode. Please switch Docker to linux mode to continue."
                    });
                }
            }

            return(capabilities);
        }
Exemplo n.º 30
0
        public void PerformProjection_RecommendationInsideStrikeWeightButOutsideTimeSlice_CorrectRating()
        {
            //setting _recommendation2.StartDateTime (02 hours) to be outside of the 2 daypart timeslices (00:00 to 01:00 && 06:00 to 08:00 hours)
            _ = _recommendation2.Setup(r => r.StartDateTime).Returns(new DateTime(2018, 1, 1, 2, 0, 0));

            _rec1obj            = _recommendation1.Object;
            _rec1obj.SpotLength = _rec1Length;
            _rec2obj            = _recommendation2.Object;
            _rec2obj.SpotLength = _rec2Length;
            var reccomendations = new List <Recommendation>()
            {
                _rec1obj, _rec2obj
            };

            var rating = CampaignProjectionProcessing.ProjectRatingsForCampaignDayPart(_dayPart, reccomendations, _targetStrikeWeightStartDate, _targetStrikeWeightEndDate, _campaignSalesAreaList);

            foreach (var key in rating)
            {
                _recommendationsTotalForDayPart += (int)key.Value;
            }

            //_recommendation2.Object has been setup to be outside of the time slices included in the day part, so the returned total should equal only to the ratings in _recommendation1.Object
            Assert.IsTrue(_recommendationsTotalForDayPart == _rec1Rating);
        }
        private void Recommend()
        {
            Radnici = Recommendation.GetSlicneRadnike(radnikId).ToList();
            foreach (var r in Radnici)
            {
                Preporuka.Add(DARadnici.RadniciOsobeSelectByIdToUpdate(r.RadnikId));
            }


            //test

            //esp_RadniciOsobeSelectById_ToUpdate_Result r = new esp_RadniciOsobeSelectById_ToUpdate_Result();
            //r.RadnikId = 1;
            //r.OsobaId = 1;
            //r.Ime = "Emir";
            //r.Prezime = "Balić";
            //r.Email = "*****@*****.**";
            //r.Telefon = "000000";
            //r.CijenaPoSatu = 123;
            //r.Status = true;
            //Preporuka.Insert(0, r);

            preporukaGrid.DataBind();
        }
Exemplo n.º 32
0
        public void PerformProjection_RecommendationInsideStrikeWeightButNonMatchingTimesliceDOW_CorrectRating()
        {
            //4th Jan 2018 = Thursday in rec2, DOW in daypart.timeslices are Mon, Tues, Wed
            _ = _recommendation2.Setup(r => r.StartDateTime).Returns(new DateTime(2018, 1, 4, 0, 0, 0));

            _rec1obj            = _recommendation1.Object;
            _rec1obj.SpotLength = _rec1Length;
            _rec2obj            = _recommendation2.Object;
            _rec2obj.SpotLength = _rec2Length;
            var reccomendations = new List <Recommendation>()
            {
                _rec1obj, _rec2obj
            };

            var rating = CampaignProjectionProcessing.ProjectRatingsForCampaignDayPart(_dayPart, reccomendations, _targetStrikeWeightStartDate, _targetStrikeWeightEndDate, _campaignSalesAreaList);

            foreach (var key in rating)
            {
                _recommendationsTotalForDayPart += (int)key.Value;
            }

            //_recommendation2.Object has been setup to be a thursday, so the returned total should equal only to the ratings in _recommendation1.Object
            Assert.IsTrue(_recommendationsTotalForDayPart == _rec1Rating);
        }
        public async Task <IActionResult> Recommend(string movieUserId, string userId)
        {
            ApplicationUser user = await GetCurrentUserAsync();

            var model = new TrackedMoviesViewModel();

            model.TrackedUserMovies = GetUserTrackedMovies(user);

            // get the user from the database
            var toUser = _context.Users.Where(u => u.Id == userId).SingleOrDefault();

            //create a record
            var recomemendation = new Recommendation()
            {
                ToUser      = toUser,
                MovieUserId = Convert.ToInt32(movieUserId)
            };


            _context.Add(recomemendation);
            await _context.SaveChangesAsync();

            return(RedirectToActionPermanent("ListTracked"));
        }
Exemplo n.º 34
0
        public void PerformProjection_MatchingRecommendationsNeighbouringTimeSlices_CorrectRating()
        {
            _ = _recommendation2.Setup(r => r.StartDateTime).Returns(new DateTime(2018, 1, 1, 2, 0, 0));

            _rec1obj            = _recommendation1.Object;
            _rec1obj.SpotLength = _rec1Length;
            _rec2obj            = _recommendation2.Object;
            _rec2obj.SpotLength = _rec2Length;
            var reccomendations = new List <Recommendation>()
            {
                _rec1obj, _rec2obj
            };

            _dayPart.Timeslices[1].FromTime = _timeslice1To;        //2 daypart timeslices set to (00:00 to 01:00 && 01:00 to 08:00 hours)
            var rating = CampaignProjectionProcessing.ProjectRatingsForCampaignDayPart(_dayPart, reccomendations, _targetStrikeWeightStartDate, _targetStrikeWeightEndDate, _campaignSalesAreaList);

            foreach (var key in rating)
            {
                _recommendationsTotalForDayPart += (int)key.Value;
            }

            //both recommendations are inside the timeslices of the day part, so the returned total should be equal to the sum of both
            Assert.IsTrue(_recommendationsTotalForDayPart == _rec1Rating - _rec2Rating);
        }
Exemplo n.º 35
0
 public Recommendation Save(Recommendation recommendation)
 {
     this.recommendationRepository.Attach(recommendation);
     return recommendation;
 }
Exemplo n.º 36
0
 public void Delete(Recommendation recommendation)
 {
     this.recommendationRepository.Detach(recommendation);
 }
Exemplo n.º 37
0
 public Recommendation Post(Recommendation recommendation)
 {
     this.recommendationService.Save(recommendation);
     return recommendation;
 }
Exemplo n.º 38
0
        public void TestRecommendationDetach()
        {
            var r = new Recommendation(7);

            this.RecommendationRepository.Detach(r);
        }
Exemplo n.º 39
0
        //Insert suggestions to database
        private void insertSuggestions(Dictionary<int, int> confidenceRatedSuggestions)
        {
            List<Recommendation> result = new List<Recommendation>();
            foreach (KeyValuePair<int, int> element in confidenceRatedSuggestions)
            {
                Recommendation r = new Recommendation();
                r.User_ID = userId;
                r.Route_ID = element.Key;
                r.Confidence = element.Value;
            //                result.Add(r);
                _db.Recommendations.InsertOnSubmit(r);
                _db.SubmitChanges();
            }

            //            _db.Recommendations.InsertAllOnSubmit(result);
            //            _db.SubmitChanges();
        }
Exemplo n.º 40
0
 private List<EMKServise.Recommendation> ConvertRecommendation(Recommendation[] c)
 {
     if (((object)c != null) && (c.Length != 0))
     {
         List<EMKServise.Recommendation> l = new List<EMKServise.Recommendation>();
         foreach (Recommendation i in c)
         {
             EMKServise.Recommendation er = new EMKServise.Recommendation();
             if (i.Date != DateTime.MinValue)
                 er.Date = i.Date;
             er.Doctor = ConvertMedicalStaff(i.Doctor);
             if (i.Text != "")
                 er.Text = i.Text;
             l.Add(er);
         }
         return l;
     }
     else
         return null;
 }
Exemplo n.º 41
0
 public int SaveRec(Recommendation r)
 {
     return DB.Save(r);
 }
Exemplo n.º 42
0
 /// <summary>
 /// There are no comments for Recommendation in the schema.
 /// </summary>
 public void AddToRecommendation(Recommendation recommendation)
 {
     base.AddObject("Recommendation", recommendation);
 }
Exemplo n.º 43
0
 /// <summary>
 /// Create a new Recommendation object.
 /// </summary>
 /// <param name="recId">Initial value of recId.</param>
 /// <param name="eventId">Initial value of eventId.</param>
 /// <param name="date">Initial value of date.</param>
 public static Recommendation CreateRecommendation(long recId, long eventId, global::System.DateTime date)
 {
     Recommendation recommendation = new Recommendation();
     recommendation.recId = recId;
     recommendation.eventId = eventId;
     recommendation.date = date;
     return recommendation;
 }
Exemplo n.º 44
0
        public void Insert(int? ParagraphActionID,DateTime? DeadlineDate,string RecommendationX,DateTime? AddedDate,DateTime? ModifiedDate,bool Deleted,DateTime? DeletedDate,int? RecommendationType,int? CommitteeID,DateTime? RecDate)
        {
            Recommendation item = new Recommendation();

            item.ParagraphActionID = ParagraphActionID;

            item.DeadlineDate = DeadlineDate;

            item.RecommendationX = RecommendationX;

            item.AddedDate = AddedDate;

            item.ModifiedDate = ModifiedDate;

            item.Deleted = Deleted;

            item.DeletedDate = DeletedDate;

            item.RecommendationType = RecommendationType;

            item.CommitteeID = CommitteeID;

            item.RecDate = RecDate;

            item.Save(UserName);
        }
Exemplo n.º 45
0
        private void SetupControls()
        {
            Recommendation blank = new Recommendation();
            blank.recID = -1;
            blank.recName = "";
            blank.recValue = "";

            cbeRecClinComboBox.Items.Add(blank);
            chemoRecClinComboBox.Items.Add(blank);
            mammoRecClinComboBox.Items.Add(blank);
            prophMastRecClinComboBox.Items.Add(blank);
            mriRecClinComboBox.Items.Add(blank);
            tvsRecClinComboBox.Items.Add(blank);
            ca125RecClinComboBox.Items.Add(blank);
            prophOophRecClinComboBox.Items.Add(blank);
            ocRecClinComboBox.Items.Add(blank);

            List<Recommendation> AllPossibleRecommendationList = new List<Recommendation>();

            AllPossibleRecommendationList = new List<Recommendation>(
                       (from dRow in SessionManager.Instance.MetaData.BrOvCdsRecs.Recs.AsEnumerable()
                        select (GetRecDataTableRow(dRow)))
                       );

            String controlName;
            foreach (Recommendation r in AllPossibleRecommendationList)
            {
                controlName = r.recName + "ClinComboBox";

                Control c = GetControlByNameIgnoreCase(controlName, this);
                if (c != null)
                {
                    ComboBox comboBox = (ComboBox)c;
                    if (comboBox.Items.Contains(r) == false)
                    {
                        comboBox.Items.Add(r);
                    }
                }
            }
        }
Exemplo n.º 46
0
        public void TestRecommendationAttach()
        {
            var criterionList = new List<Criterion>()
            {
                new Criteria3() {
                    TestProperty = "testing 7"
                }
                //new Criteria1() {
                //    A = 2,
                //    B = 3,
                //    C = 3,
                //    D = 1,
                //    E = 2
                //},
                //new Criteria2() {
                //    ProvideData = false,
                //    Criteria21a = new Criteria21a() {
                //        ProteinContentFeed = 6,
                //        EFCR = 4,
                //        ProteinContentHarvested = 3,
                //        NitrogenInput = 8,
                //        Score = 7
                //    },
                //    Criteria21b = new Criteria21b() {
                //        AdjustmentOther = true,
                //        AdjustmentOtherAmount = 4,
                //        AdjustmentSettlingPond = 3,
                //        AdjustmentSettlingPondForHarvest = 5,
                //        BasicScore = 8,
                //        IMTA = true,
                //        IMTAAdjustment = 2,
                //        ProductionSystemOpenModified = ProductionSystemOpenModified.Open,
                //        ProductionSystemType = ProductionSystemType.netCagesAndPens
                //    },
                //    Criteria22a = new Criteria22a() {
                //        A = 1,
                //        B = 2,
                //        C = 3,
                //        D = 4,
                //        E = 5
                //    },
                //    Criteria22b = new Criteria22b() {
                //        A = 5,
                //        B = 4,
                //        C = 3,
                //        D = 2,
                //        E = 1
                //    }
                //}
            };

            var rec = new Recommendation()
            {
                Name = "new rec test",
                Report = new Report(1),
                Criterion = criterionList,
                OtherSpecifics = "other specs test",
                Certification = "cert 3"//,
                //ProductionMethods = new List<ProductionMethod>()
                //{
                //    new ProductionMethod(5) {
                //        Method = "Troll/Pole",
                //        Aliases = "Wild-Hook/Line",
                //        IsFarmed = false
                //    }
                //},
                //Regions = new List<Region>()
                //{
                //    new Region(7) {
                //        Description = "Bahamas",
                //        IndentLevel = 0,
                //        SortOrder = 0,
                //        ParentId = 0
                //    }
                //},
                //Species = new List<Species>()
                //{
                //    new Species(9) {
                //        CommonName = "Barramundi",
                //        Genus = "Lates",
                //        SpeciesName = "calcarifer",
                //        Inactive = false
                //    }
                //}
            };

            this.RecommendationRepository.Attach(rec);
        }
Exemplo n.º 47
0
        private void SetupRecDropDowns()
        {
            Recommendation blank = new Recommendation();
            blank.recID = -1;
            blank.recName = "";
            blank.recValue = "";

            Recommendation na = new Recommendation();
            na.recID = -1;
            na.recName = "";
            na.recValue = "N/A";

            genTestRecClinComboBox.Items.Add(blank);
            MmrTestRecComboBox.Items.Add(blank);
            MmrTestResultComboBox.Items.Add(blank);
            ScreeningRecComboBox.Items.Add(blank);
            GenTestresultComboBox.Items.Add(blank);

            genTestRecClinComboBox.Items.Add(na);
            MmrTestRecComboBox.Items.Add(na);
            MmrTestResultComboBox.Items.Add(na);
            ScreeningRecComboBox.Items.Add(na);
            GenTestresultComboBox.Items.Add(na);

            List<Recommendation> AllPossibleRecommendationList = new List<Recommendation>();
            AllPossibleRecommendationList = new List<Recommendation>(
               (from dRow in SessionManager.Instance.MetaData.BrOvCdsRecs.Recs.AsEnumerable()
            select (GetRecDataTableRow(dRow)))
               );

            foreach (Recommendation r in AllPossibleRecommendationList)
            {
                if (proband.gender.ToLower().StartsWith("f"))
                {
                    if (r.recValue.Contains(" Male"))
                    {
                        continue;
                    }
                    else
                    {
                        r.recValue = r.recValue.Replace(" Female", "");
                    }
                }
                else
                {
                    if (r.recValue.Contains(" Female"))
                    {
                        continue;
                    }
                    else
                    {
                        r.recValue = r.recValue.Replace(" Male", "");
                    }
                }

                if (string.Compare(r.recName, "genTestRec", true) == 0)
                {
                    genTestRecClinComboBox.Items.Add(r);
                }
                else if (string.Compare(r.recName, "Breast Density", true) == 0)
                {
                    ScreeningRecComboBox.Items.Add(r);
                }
                else if (string.Compare(r.recName, "GenTestResult", true) == 0)
                {
                    GenTestresultComboBox.Items.Add(r);
                }
                else if (string.Compare(r.recName, "ColonGenTestRec", true) == 0)
                {
                    MmrTestRecComboBox.Items.Add(r);
                }
                else if (string.Compare(r.recName, "ColonGenTestResult", true) == 0)
                {
                    MmrTestResultComboBox.Items.Add(r);
                }
            }
        }
Exemplo n.º 48
0
 public void Delete(Recommendation recommendation)
 {
     this.recommendationService.Delete(recommendation);
 }
 public void Add(Recommendation item)
 {
     this.Session.Save(item);
 }
Exemplo n.º 50
0
 public void Attach(Recommendation model)
 {
     RunInTransaction(session => session.SaveOrUpdate(model));
 }
Exemplo n.º 51
0
 private Recommendation GetRecDataTableRow(DataRow dr)
 {
     Recommendation oRec = new Recommendation();
     oRec.recID = (int)dr["recID"];
     oRec.recName = dr["recName"].ToString();
     oRec.recValue = dr["recValue"].ToString();
     oRec.paragraph = dr["paragraph"].ToString();
     if (dr["bullet"] != null)
     {
         oRec.bullet = dr["bullet"].ToString();
     }
     oRec.patientParagraph = dr["patientParagraph"].ToString();
     return oRec;
 }