Наследование: MonoBehaviour
Пример #1
0
        public RecipeRater(IKPCContext context, Recipe recipe, Rating rating)
        {
            this.context = context;
            this.newRatings = new Dictionary<Recipe, Rating>();

            this.newRatings.Add(recipe, rating);
        }
Пример #2
0
        public double Rate(int clinicId, string userId, int ratingValue)
        {
            var rating = this.ratings.All().FirstOrDefault(x => x.AuthorId == userId && x.ClinicId == clinicId);

            if (rating == null)
            {
                rating = new Rating()
                {
                    AuthorId = userId,
                    ClinicId = clinicId,
                    Value = ratingValue
                };

                this.ratings.Add(rating);
            }
            else
            {
                rating.Value = ratingValue;
            }

            this.ratings.Save();

            double clinicRating = this.ratings
                .All()
                .Where(x => x.ClinicId == clinicId)
                .Average(x => x.Value);

            return clinicRating;
        }
Пример #3
0
        public void UpdateProductRating(Rating r)
        {
            entities.Rating.Attach(GetRating(r.ProductID,r.Username));
            entities.Rating.ApplyCurrentValues(r);

            entities.SaveChanges();
        }
 public Task<List<ImageResult>> Search(string search, Rating rating = Rating.Strict, ResultSize resultSize = ResultSize.Twenty, int offset = 0)
 {
     return Task.Run<List<ImageResult>>(() =>
                                            {
                                                return new List<ImageResult>();
                                            });
 }
Пример #5
0
 internal Picture(string name, string displayName, Rating rating, IEnumerable<Category> categories)
 {
     this.name = name;
     this.displayName = displayName;
     this.rating = rating;
     this.categories = ImmutableHashSet.Create(categories);
 }
        /// <summary>
        /// Returns a Globally Recognised Avatar as an &lt;img /&gt; - http://gravatar.com
        /// </summary>
        /// <param name="emailAddress">Email Address for the Gravatar</param>
        /// <param name="defaultImage">Default image if user hasn't created a Gravatar</param>
        /// <param name="size">Size in pixels (default: 80)</param>
        /// <param name="defaultImageUrl">URL to a custom default image (e.g: 'Url.Content("~/images/no-grvatar.png")' )</param>
        /// <param name="forceDefaultImage">Prefer the default image over the users own Gravatar</param>
        /// <param name="rating">Gravatar content rating (note that Gravatars are self-rated)</param>
        /// <param name="forceSecureRequest">Always do secure (https) requests</param>
        public static HtmlString GravatarImage(
          this HtmlHelper htmlHelper,
          string emailAddress,
          int size = 80,
          DefaultImage defaultImage = DefaultImage.Default,
          string defaultImageUrl = "",
          bool forceDefaultImage = false,
          Rating rating = Rating.G,
          bool forceSecureRequest = false)
        {
            var imgTag = new TagBuilder("img");

            emailAddress = string.IsNullOrEmpty(emailAddress) ? string.Empty : emailAddress.Trim().ToLower();

            imgTag.Attributes.Add("src",
                string.Format("{0}://{1}.gravatar.com/avatar/{2}?s={3}{4}{5}{6}",
                    htmlHelper.ViewContext.HttpContext.Request.IsSecureConnection || forceSecureRequest ? "https" : "http",
                    htmlHelper.ViewContext.HttpContext.Request.IsSecureConnection || forceSecureRequest ? "secure" : "www",
                    GetMd5Hash(emailAddress),
                    size.ToString(),
                    "&d=" + (!string.IsNullOrEmpty(defaultImageUrl) ? HttpUtility.UrlEncode(defaultImageUrl) : defaultImage.GetDescription()),
                    forceDefaultImage ? "&f=y" : "",
                    "&r=" + rating.GetDescription()
                    )
                );

            //imgTag.Attributes.Add("class", "gravatar");
            imgTag.Attributes.Add("class", "uk-border-rounded");
            imgTag.Attributes.Add("alt", "Gravatar image");
            return new HtmlString(imgTag.ToString(TagRenderMode.SelfClosing));
        }
Пример #7
0
 public void Reset()
 {
     m_LastScore = Rating.None;
     m_Score = Rating.None;
     m_LastTotalScore = 0;
     m_TotalScore = 0;
 }
Пример #8
0
        public void AddRatingToRecipe(Rating rate, Recipe r, User u)
        {
            SqlConnection con = CreateConnection();

            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandText = "AddRatingToRecipe";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@recipeID", r.Id);
                cmd.Parameters.AddWithValue("@userID", u.Id);
                cmd.Parameters.AddWithValue("@rating", rate);

                cmd.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                throw /*ex*/;
            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }
Пример #9
0
 /// <summary> 
 /// Full constructor. 
 /// </summary>
 public Comment(Rating rating, string text, User fromUser, Item item)
 {
     this.rating = rating;
     this.text = text;
     this.fromUser = fromUser;
     this.item = item;
 }
        public ActionResult CreateRating([DataSourceRequest]DataSourceRequest request, IEnumerable<AdministrationRatingsViewModel> models)
        {
            var result = new List<AdministrationRatingsViewModel>();
            if (this.ModelState.IsValid && models != null)
            {
                foreach (var model in models)
                {
                    var ratingUser = this.users.GetByUsername(model.UserName).FirstOrDefault();
                    var petToUpdate = this.pets.GetByIntId(model.PetId).FirstOrDefault();
                    if (ratingUser != null && petToUpdate != null)
                    {
                        var newRating = new Rating { RatingValue = model.RatingValue, PetId = model.PetId, Author = ratingUser };
                        this.ratings.Add(newRating);
                        petToUpdate.CurrentRating = petToUpdate.Ratings.Average(r => r.RatingValue);
                        this.pets.Update(petToUpdate);
                        model.CreatedOn = newRating.CreatedOn;
                        model.Id = newRating.Id;
                        result.Add(model);
                    }
                }

                return this.Json(result.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
            }

            return null;
        }
		public bool Execute ()
		{
			this.CreateDialog ("rating_filter_dialog");
			
			if (query.RatingRange != null) {
				minrating_value = (int) query.RatingRange.MinRating;
				maxrating_value = (int) query.RatingRange.MaxRating;
			}
			minrating = new Rating (minrating_value);
			maxrating = new Rating (maxrating_value);
			minrating_hbox.PackStart (minrating, false, false, 0);
			maxrating_hbox.PackStart (maxrating, false, false, 0);

			Dialog.TransientFor = parent_window;
			Dialog.DefaultResponse = ResponseType.Ok;

			ResponseType response = (ResponseType) this.Dialog.Run ();

			bool success = false;

			if (response == ResponseType.Ok) {
				query.RatingRange = new RatingRange ((uint) minrating.Value, (uint) maxrating.Value);
				success = true;
			}
			
			this.Dialog.Destroy ();
			return success;
		}
Пример #12
0
 public static Loan CreateTermLoan(decimal amount, DateTime start, DateTime maturity, Rating riskRating, IRiskFactor factors)
 {
     var loan = new Loan(null, maturity, amount, amount, factors, null);
     loan.riskRating = riskRating;
     loan.start = start;
     return loan;
 }
 public async Task LoadMore(SearchInstance instance, Rating rating, ResultSize resultSize)
 {
     var imagesToAdd = await Search(instance.Query, rating, resultSize, instance.Images.Count + 1);
     foreach (var image in imagesToAdd)
     {
         instance.Images.Add(image);
     }
 }
        /// <summary>
        /// Gets the URI of the Gravatar image for the specifications.
        /// </summary>
        /// <param name="urlHelper">The UrlHelper object getting the URI.</param>
        /// <param name="email">The email whose Gravatar source should be returned.</param>
        /// <param name="size">The size of the requested Gravatar.</param>
        /// <param name="defaultImage">The default image to return if no Gravatar is found for the specified <paramref name="email"/>.</param>
        /// <param name="maxRating">The maximum Gravatar rating to allow for requested images..</param>
        /// <returns>The URI of the Gravatar for the specifications.</returns>
        public static string Gravatar(this UrlHelper urlHelper, string email, int? size, string defaultImage, Rating? maxRating) {
            var gravatar = new Gravatar();
            gravatar.DefaultImage = defaultImage;
            if (size.HasValue) gravatar.Size = size.Value;
            if (maxRating.HasValue) gravatar.MaxRating = maxRating.Value;

            return gravatar.GetImageSource(email);
        }
Пример #15
0
        public static int PointsExchanged(Rating winnerRating, Rating loserRating)
        {
            var difference = (double)loserRating.Value - winnerRating.Value;
            var expected = 1 / (1 + (Math.Pow(10,(difference/Volatility))));

            var exchanged = (Int32)Math.Round((Factor * (1 - expected)), MidpointRounding.AwayFromZero);
            return exchanged;
        }
Пример #16
0
 public GestureKey(Rating rating, string name, DateTime recorded, int framenum, TimeSpan timestamp)
 {
     this.rating = rating;
     this.name = name;
     this.recorded = recorded;
     this.framenum = framenum;
     this.timestamp = timestamp;
 }
Пример #17
0
        public void AddRating(int postId, byte value, string authorId)
        {
            var newRating = new Rating { PostId = postId, Value = value, AuthorId = authorId };

            this.ratings.Add(newRating);

            this.ratings.SaveChanges();
        }
Пример #18
0
        /// <summary>
        /// Add a rating to the product
        /// </summary>
        /// <param name="r">The rating to be added</param>
        public void AddProductRating(Rating r)
        {
            if (r.Rating1 < 0)
                r.Rating1 = 0;
            else if (r.Rating1 > 5)
                r.Rating1 = 5;

               new RatingRep().AddProductRating(r);
        }
Пример #19
0
        void RateGameMenuEntrySelected(object sender, PlayerIndexEventArgs e)
        {
            currentRating++;

            if (currentRating > Rating.Superb)
                currentRating = 0;

            SetMenuEntryText();
        }
Пример #20
0
        public void EqualityIgnoresTime()
        {
            var r1000_1 = new Rating { Value = 1000, TimeFrom = DateTime.UtcNow};
            var r1000_2 = new Rating { Value = 1000, TimeFrom = DateTime.UtcNow.AddHours(1)};
            var r1002 = new Rating { Value = 1002 };

            Assert.AreEqual(r1000_1, r1000_2);
            Assert.AreNotEqual(r1000_1, r1002);
        }
Пример #21
0
		public static string GetURL (string email, int size, Rating rating = Rating.PG)
		{
			var hash = MD5Hash (email.ToLower ());

			if (size < 1 | size > 600) {
				throw new ArgumentOutOfRangeException("size", "The image size should be between 20 and 80");
			}

			return _url + hash + "&s=" + size.ToString () + "&r=" + rating.ToString ().ToLower ();
		}
Пример #22
0
 /// <summary>
 /// Gets an img tag of the Gravatar for the supplied specifications.
 /// </summary>
 /// <param name="htmlHelper">The HtmlHelper object that does the rendering.</param>
 /// <param name="email">The email address whose Gravatar should be rendered.</param>
 /// <param name="size">The size of the rendered Gravatar.</param>
 /// <param name="defaultImage">The default image to display if no Gravatar exists for the specified <paramref name="email"/>.</param>
 /// <param name="maxRating">The maximum Gravatar rating to allow for rendered Gravatars.</param>
 /// <param name="htmlAttributes">Additional attributes to include in the rendered tag.</param>
 /// <returns>An HTML string of the rendered img tag.</returns>
 public static MvcHtmlString Gravatar(
     this HtmlHelper htmlHelper,
     string email,
     int? size,
     string defaultImage,
     Rating? maxRating,
     object htmlAttributes
 ) {
     return Gravatar(htmlHelper, email, size, defaultImage, maxRating, DictionaryFromObject(htmlAttributes));
 }
Пример #23
0
        public RegexScraper(string name, Uri url, Regex regex,
			string displayName, Rating rating, IEnumerable<Category> categories)
        {
            m_name = name;
            m_url = url;
            m_regex = regex;
            m_displayName = displayName;
            m_rating = rating;
            m_categories = ImmutableHashSet.Create(categories);
        }
 public virtual void RatingCreatesAutomationPeer()
 {
     Rating acc = new Rating();
     RatingAutomationPeer peer = null;
     TestAsync(
         acc,
         () => peer = FrameworkElementAutomationPeer.CreatePeerForElement(acc) as RatingAutomationPeer,
         () => Assert.IsNotNull(peer, "Rating peer should not be null!"),
         () => Assert.AreEqual(acc, peer.Owner, "Rating should be owner of the peer!"));
 }
Пример #25
0
        // Adding to settings tab: Add, Edit, Delete a movie options
        // Add: Blank form where you insert title, pic, desc, etc...
        // Edit: inherit from add except all fields are filled by dragging & dropping a movie into the form: it will fill all fields
        // Delete: Just search for a title and if it exists, it will be removed
        public TabScreen(string username,string imageLocation)
        {
            InitializeComponent();

            this.username = username;
            this.imageLocation = imageLocation;

            //set up the profile area
            usernameLabel.Text = username;
            profilePictureBox.ImageLocation = imageLocation;
            profilePictureBox.SizeMode = PictureBoxSizeMode.StretchImage;

            //make the tabe take up the top of the screeen
            tabControl.SizeMode = TabSizeMode.Fixed;
            tabControl.ItemSize = new Size(tabControl.Width / tabControl.TabCount-1, 30); //need to take away 1 so the tabs dont take up too much space.

            //set up the dictionary of sorting patterns
            sortBy = new Dictionary<string, SortBy>();
            sortBy.Add("Alphabetical", SortBy.Alphabetical);
            sortBy.Add("Rating", SortBy.Rating);
            sortBy.Add("Year", SortBy.Year);

            ratingsMap = new Dictionary<string, Rating>();
            ratingsMap.Add("R", Rating.R);
            ratingsMap.Add("U", Rating.R);
            ratingsMap.Add("PG-14", Rating.PG13);
            ratingsMap.Add("PG-13", Rating.PG13);
            ratingsMap.Add("PG", Rating.PG);
            ratingsMap.Add("G", Rating.G);

            supressEvents = false;

            tags = getTags();

            var doc = System.Xml.Linq.XDocument.Load("users.xml");

            foreach (XElement element in doc.Element("users").Elements())
            {
                if (username.Equals(element.Element("name").Value))
                {
                    if(element.Element("max_rating").Value.Equals("None"))
                    {
                        maxRating = Rating.R;
                    }
                    else
                    {
                        maxRating = ratingsMap[element.Element("max_rating").Value];
                    }

                }
            }

            //resize the screen to avoid the tab-bug
            this.Size = new Size(this.Size.Width + 1, this.Size.Height);
        }
Пример #26
0
 public IActionResult Create(Rating rating)
 {
     if (ModelState.IsValid)
     {
         _context.Rating.Add(rating);
         _context.SaveChanges();
         return RedirectToAction("Index");
     }
     ViewData["CarrierID"] = new SelectList(_context.Carrier, "CarrierID", "Carrier", rating.CarrierID);
     return View(rating);
 }
Пример #27
0
		public static string GetURL(string email, int size, Rating rating = Rating.PG)
		{
			var hash = MD5Hash(email.ToLower());

			if (size < 1 | size > 600)
			{
				throw new ArgumentOutOfRangeException("size", "The image size should be between 20 and 80");
			}

			return string.Format("{0}{1}&s={2}&r={3}", _url, hash, size, rating.ToString().ToLower());
		}
Пример #28
0
        public void OrderingWorksAsExpected()
        {
            var r1000 = new Rating {Value = 1000};
            var r1001 = new Rating { Value = 1001 };
            var r1002 = new Rating { Value = 1002 };

            var inputArray = new[] {r1001, r1000, r1002};
            var orderedArray = inputArray.OrderBy(r => r).ToArray();

            Assert.AreEqual(new[] {r1000, r1001, r1002}, orderedArray);
        }
        public async Task<List<ImageResult>> Search(string search, Rating rating = Rating.Strict, ResultSize resultSize = ResultSize.Twenty, int offset = 0)
        {
            var images = new List<ImageResult>();

            var context = new BingSearchContainer(new Uri("https://api.datamarket.azure.com/Data.ashx/Bing/Search"));
            context.Credentials = new NetworkCredential(_api, _api);
            var result = await context.Image(search, "en-US", rating, resultSize, offset).ExecuteAsync();
            
            images.AddRange(result.ToList());

            return images;
        }
Пример #30
0
 public Rating ThirdRating()
 {
     var thirdRating = new Rating
     {
         RatingId = 3,
         ItemAccuracy = 4,
         Communication = 1,
         DeliveryTime = 2,
         Overall = 1,
     };
     return thirdRating;
 }
Пример #31
0
 public override string ToString() => Name + " " + Rating.ToShortString() + " " + Date.ToString();
Пример #32
0
 public RatingChangeMessage(object sender, Rating rating) : base(sender)
 {
     Rating = rating;
 }
Пример #33
0
 public void Add(Rating rating)
 {
     _ratingDal.Add(rating);
 }
Пример #34
0
 public void SetRating(Rating rating)
 {
     this.rating = rating;
 }
Пример #35
0
        public async Task <IActionResult> rate([FromBody] RatingViewModel[] ratings)  //оценка поста
        {
            ClaimsPrincipal currentUser = this.User;
            string          userid      = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;
            double          amount      = 0;

            foreach (RatingViewModel item in ratings) //смотрим, сколько всего критериев. это нужно для рассчёта веса
            {
                amount += Math.Pow(2, Convert.ToInt32(item.weight));
            }
            double alpha  = 1 / amount; //рассчёт веса критериев
            float  result = 0;

            //result += Convert.ToSingle(alpha);
            foreach (RatingViewModel item in ratings)
            {
                result += Convert.ToSingle(Convert.ToInt32(item.rating) * Math.Pow(2, Convert.ToInt32(item.weight)) * alpha);                            //вычисление рейтинга БЕЗ поправки на вес голоса пользователя
                Rating newrate = new Rating();                                                                                                           //создаём запись оценки
                newrate.CriterionId = Convert.ToInt16(item.criterion);                                                                                   //задаём критерий
                newrate.PostId      = Convert.ToInt16(item.post);                                                                                        //id поста
                newrate.UserId      = userid;                                                                                                            //пользователя
                newrate.rating      = Convert.ToSingle(Math.Round(Convert.ToInt32(item.rating) * Math.Pow(2, Convert.ToInt32(item.weight)) * alpha, 3)); //оценку округляем до 3 знаков после запятой
                _context.Add(newrate);
                await _context.SaveChangesAsync();
            }
            Math.Round(result, 3);
            int  theid     = Convert.ToInt32(ratings[0].post);
            Post ratedpost = await _context.Posts.Include(p => p.User).Include(p => p.Category).SingleOrDefaultAsync(p => p.PostID == theid); //здесь готовый рейтинг умножается на вес пользователя и плюсуется к рейтингу поста

            //я не уверен, надо ли оно, но пускай пока будет
            ratedpost.rating += result;
            _context.Update(ratedpost);
            await _context.SaveChangesAsync();

            //----
            CommentViewModel model = new CommentViewModel();

            model.post  = ratedpost;
            model.crits = _context.CatCrits.Where(p => p.CategoryId == ratedpost.CategoryId).Include(p => p.Category).Include(p => p.Criterion);
            var   rates = _context.Ratings.Where(p => p.PostId == theid).Include(p => p.User);
            float sum   = 0;

            foreach (Rating item in rates)
            {
                sum += item.rating * item.User.Weight;
            }
            model.post.rating = sum;
            //--------------------------проверка на доступность оценки---------------------------------
            model.rateable = true;
            if (ratedpost.UserId == userid)
            {
                model.rateable = false;
            }
            else
            {
                bool check = _context.Ratings.Any(p => (p.PostId == ratedpost.PostID) && (p.UserId == userid));
                if (check == true)
                {
                    model.rateable = false;
                }
                else
                {
                    model.rateable = true;
                }
            }
            model.userrating = 0;
            if (model.rateable == false)
            {
                foreach (Rating your in rates)
                {
                    if (your.UserId == userid)
                    {
                        model.userrating += your.rating * your.User.Weight;
                    }
                }
            }
            //---------------------првоерка на доступность редактирования---------------------------
            if (userid == ratedpost.UserId)
            {
                model.editable = true;
            }
            else
            {
                model.editable = false;
            }
            return(PartialView("posthead", model));
        }
Пример #36
0
 public Rating Update(Rating entity)
 {
     throw new System.NotImplementedException();
 }
Пример #37
0
        public BlogService()
        {
            Author DinoEsposito = new Author
            {
                Id         = 1,
                Name       = "Dinoe Esposito",
                Bio        = "Dino Esposito has authored more than 20 books and 1,000 articles in ...",
                ImgUrl     = "https://secure.ssgravatar.com/avatar/ace158af8dfab0e682dcc70d965514e5?s=80&d=mm&r=g",
                ProfileUrl = "https://www.red-gate.com/simple-talk/author/dino-esposito/"
            };
            Author LanceTalbert = new Author
            {
                Id         = 2,
                Name       = "Lance Talbert",
                Bio        = "Lance Talbert is a budding game developer that has been learning to program since ...",
                ImgUrl     = "https:/s/www.red-gate.com/simple-talk/wp-content/uploads/2018/01/red-gate-bio-pic.jpg",
                ProfileUrl = "https://www.red-gate.com/simple-talk/author/lancetalbert/"
            };

            authors.Add(DinoEsposito);
            authors.Add(LanceTalbert);
            Comment comment1 = new Comment
            {
                Url         = "https://#",
                Description = "Bla bla bla",
                Count       = 1
            };
            Comment comment2 = new Comment
            {
                Url         = "https://#",
                Description = "Bla bla bla",
                Count       = 4
            };
            Rating rating1 = new Rating
            {
                Percent = 98,
                Count   = 1
            };
            Rating rating2 = new Rating
            {
                Percent = 95,
                Count   = 5
            };
            Post FormsInVanilla = new Post
            {
                Id          = 1,
                Title       = "Building Better HTML Forms in Vanilla-JS",
                Description = "Creating forms is one of the most basic skills for a web developer...",
                Date        = DateTime.Today,
                Url         = "https://www.red-gate.com/simple-talk/dotnet/net-development/building-better-html-forms-in-vanilla-js/",
                Author      = DinoEsposito,
                Comments    = new List <Comment>()
                {
                    comment1
                },
                Rating     = rating1,
                Categories = new string[] { ".NET Development" }
            };
            Post VoiceCommands = new Post
            {
                Id          = 2,
                Title       = "Voice Commands in Unity",
                Description = "Today, we use voice in many ways. We can order groceries...",
                Date        = DateTime.Today,
                Url         = "https://www.red-gate.com/simple-talk/dotnet/c-programming/voice-commands-in-unity/",
                Author      = LanceTalbert,
                Comments    = new List <Comment>()
                {
                    comment2
                },
                Rating     = rating2,
                Categories = new string[] { "C# programming" }
            };

            posts.Add(FormsInVanilla);
            posts.Add(VoiceCommands);
            SocialNetwork sn1 = new SocialNetwork()
            {
                Type     = SNType.INSTAGRAM,
                Author   = DinoEsposito,
                NickName = "@dino",
                Url      = "https://#"
            };
            SocialNetwork sn2 = new SocialNetwork()
            {
                Type     = SNType.TWITTER,
                Author   = DinoEsposito,
                NickName = "@dino",
                Url      = "https://#"
            };

            sns.Add(sn1);
            sns.Add(sn2);
        }
Пример #38
0
    protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
    {
        if (e.Item is GridEditableItem && e.Item.IsInEditMode)
        {
            var itemtype      = e.Item.ItemType;
            var row           = itemtype == GridItemType.EditFormItem ? (GridEditFormItem)e.Item : (GridEditFormInsertItem)e.Item;
            var FileImageName = (RadUpload)row.FindControl("FileImageName");

            var dv                      = (DataView)ObjectDataSource1.Select();
            var ProductID               = ((HiddenField)row.FindControl("hdnProductID")).Value;
            var ddlCategory             = (RadComboBox)row.FindControl("ddlCategory");
            var ddlManufacturer         = (RadComboBox)row.FindControl("ddlManufacturer");
            var ddlProductGender        = (RadComboBox)row.FindControl("ddProductGender");
            var ddlProductMaterialColor = (RadComboBox)row.FindControl("ddlProductMaterialColor");
            var ddlProductSpecies       = (RadComboBox)row.FindControl("ddlProductSpecies");
            var ddlProductStoneColor    = (RadComboBox)row.FindControl("ddlProductStoneColor");
            var ddlProductStoneCategory = (RadComboBox)row.FindControl("ddlProductStoneCategory");
            var ddlProductGoldenAge     = (RadComboBox)row.FindControl("ddlProductGoldenAge");
            var ddlOrigin               = (RadComboBox)row.FindControl("ddlOrigin");

            if (!string.IsNullOrEmpty(ProductID))
            {
                dv.RowFilter = "ProductID = " + ProductID;

                if (!string.IsNullOrEmpty(dv[0]["CategoryID"].ToString()))
                {
                    ddlCategory.SelectedValue = dv[0]["CategoryID"].ToString();
                }
                if (!string.IsNullOrEmpty(dv[0]["ManufacturerID"].ToString()))
                {
                    ddlManufacturer.SelectedValue = dv[0]["ManufacturerID"].ToString();
                }
                if (!string.IsNullOrEmpty(dv[0]["ProductGenderID"].ToString()))
                {
                    ddlProductGender.SelectedValue = dv[0]["ProductGenderID"].ToString();
                }
                if (!string.IsNullOrEmpty(dv[0]["ProductMaterialColorID"].ToString()))
                {
                    ddlProductMaterialColor.SelectedValue = dv[0]["ProductMaterialColorID"].ToString();
                }
                if (!string.IsNullOrEmpty(dv[0]["ProductSpeciesID"].ToString()))
                {
                    ddlProductSpecies.SelectedValue = dv[0]["ProductSpeciesID"].ToString();
                }
                if (!string.IsNullOrEmpty(dv[0]["ProductStoneColorID"].ToString()))
                {
                    ddlProductStoneColor.SelectedValue = dv[0]["ProductStoneColorID"].ToString();
                }
                if (!string.IsNullOrEmpty(dv[0]["ProductStoneCategoryID"].ToString()))
                {
                    ddlProductStoneCategory.SelectedValue = dv[0]["ProductStoneCategoryID"].ToString();
                }
                if (!string.IsNullOrEmpty(dv[0]["ProductGoldenAgeID"].ToString()))
                {
                    ddlProductGoldenAge.SelectedValue = dv[0]["ProductGoldenAgeID"].ToString();
                }
                if (!string.IsNullOrEmpty(dv[0]["OriginID"].ToString()))
                {
                    ddlOrigin.SelectedValue = dv[0]["OriginID"].ToString();
                }
            }
            else
            {
                ddlCategory.SelectedValue     = ddlSearchCategory.SelectedValue;
                ddlManufacturer.SelectedValue = ddlSearchManufacturer.SelectedValue;
                ddlOrigin.SelectedValue       = ddlSearchOrigin.SelectedValue;
            }
            RadAjaxPanel1.ResponseScripts.Add(string.Format("window['UploadId'] = '{0}';", FileImageName.ClientID));
        }
        else if (e.Item is GridDataItem)
        {
            var ContentRating1 = (Spaanjaars.Toolkit.ContentRating)e.Item.FindControl("ContentRating1");
            var oRating        = new Rating();
            var ProductID      = ((GridDataItem)e.Item).GetDataKeyValue("ProductID").ToString();
            ContentRating1.ItemId     = ProductID;
            ContentRating1.DataSource = oRating.RatingSelectAll(ProductID);
            ContentRating1.DataBind();
        }
    }
Пример #39
0
        void create()
        {
            Grid grid = new Grid();

            grid.HorizontalAlignment = HorizontalAlignment.Center;
            grid.VerticalAlignment   = VerticalAlignment.Center;
            grid.Background          = null;

            Rating ratingControl = new Rating();

            ratingControl.HorizontalAlignment = HorizontalAlignment.Left;
            ratingControl.VerticalAlignment   = VerticalAlignment.Top;
            ratingControl.ItemCount           = 5;
            ratingControl.Foreground          = new SolidColorBrush(Colors.Red);
            ratingControl.Background          = null;
            ratingControl.IsReadOnly          = true;
            ratingControl.SelectionMode       = RatingSelectionMode.Continuous;

            double scale = 0.6;

            ratingControl.LayoutTransform = new ScaleTransform(scale, scale);

            grid.Children.Add(ratingControl);

            int i = 0;

            double nrStars = 0;

            do
            {
                ratingControl.Value = nrStars;

                grid.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
                grid.Arrange(new Rect(new Size(double.MaxValue, double.MaxValue)));
                Rect size = VisualTreeHelper.GetDescendantBounds(ratingControl);
                //grid.Arrange(new Rect(new Size(size.Width, size.Height)));

                RenderTargetBitmap bitmap = new RenderTargetBitmap((int)(size.Width * scale), (int)(size.Height * scale),
                                                                   96, 96, PixelFormats.Default);

                Window dummy = new Window();
                dummy.Content       = grid;
                dummy.SizeToContent = SizeToContent.WidthAndHeight;
                dummy.Show();

                bitmap.Render(ratingControl);

                RatingBitmap.Add(bitmap);

                nrStars += 1.0 / 5;

                BitmapEncoder encoder = new PngBitmapEncoder();

                encoder.Frames.Add(BitmapFrame.Create(bitmap, null, null, null));

                FileStream outputFile = new FileStream("d:\\" + i + "stars.png", FileMode.Create);

                encoder.Save(outputFile);

                i++;
            } while (nrStars <= 1);
        }
Пример #40
0
        // *********************************************************************
        //  HandleDataBindingForPostCell
        //
        /// <summary>
        /// Databinds the post cell
        /// </summary>
        /// <remarks>
        /// Used only if a user defined template is not provided.
        /// </remarks>
        ///
        // ********************************************************************/
        private void HandleDataBindingForPostCell(Object sender, EventArgs e)
        {
            Table     table;
            TableRow  tr;
            TableCell td;
            Label     label;
            string    dateFormat;
            DateTime  postDateTime;
            User      postUser;

            // Get the sender
            TableCell    postInfo  = (TableCell)sender;
            DataListItem container = (DataListItem)postInfo.NamingContainer;
            Post         post      = (Post)container.DataItem;

            // Get the user that created the post
            postUser = Users.GetUserInfo(post.Username, false);

            // Create the table
            table             = new Table();
            table.CellPadding = 3;
            table.CellSpacing = 0;
            table.Width       = Unit.Percentage(100);

            // Row 1
            tr          = new TableRow();
            td          = new TableCell();
            td.CssClass = "forumRowHighlight";

            // Add in Subject
            label          = new Label();
            label.CssClass = "normalTextSmallBold";
            label.Text     = post.Subject + "<a name=\"" + post.PostID + "\"/>";
            td.Controls.Add(label);

            td.Controls.Add(new LiteralControl("<br>"));

            // Add in 'Posted: '
            label          = new Label();
            label.CssClass = "normalTextSmaller";
            label.Text     = " Posted: ";
            td.Controls.Add(label);

            // Get the postDateTime
            postDateTime = post.PostDate;

            // Personalize
            if (user != null)
            {
                dateFormat   = user.DateFormat;
                postDateTime = Users.AdjustForTimezone(postDateTime, user);
            }
            else
            {
                dateFormat = Globals.DateFormat;
            }

            // Add in PostDateTime
            label          = new Label();
            label.CssClass = "normalTextSmaller";
            label.Text     = postDateTime.ToString(dateFormat + " " + Globals.TimeFormat);
            td.Controls.Add(label);

            // Ratings --
            // Get the rating from the database and display it in textual
            // form and using the progress bar.
            if (post.PostType == Posts.PostType.Rating)
            {
                Rating rating = Ratings.GetRating(post.PostID);
                td.Controls.Add(new LiteralControl("<br>"));
                Label ratingLabel = new Label();
                ratingLabel.CssClass = "normalTextSmallBold";
                ratingLabel.Text     = "Rating: (" + rating.Value + "/5)";
                td.Controls.Add(ratingLabel);
                ProgressBar pb = new ProgressBar();
                pb.BackColor            = System.Drawing.Color.DarkGray;
                pb.PercentageOfProgress = rating.Value * 20;
                td.Controls.Add(pb);
            }

            // Add column 1
            tr.Controls.Add(td);

/*
 * TODO: Enable Rating of posts
 *          td = new TableCell();
 *          td.CssClass = "forumRowHighlight";
 *          td.HorizontalAlign = HorizontalAlign.Right;
 *          td.VerticalAlign = VerticalAlign.Top;
 *          td.Text= "<a href>Rate this post</a>&nbsp;" ;
 *          tr.Controls.Add(td);
 */
            table.Controls.Add(tr);

            tr.Controls.Add(td);
            table.Controls.Add(tr);

            // Row 2 (body)
            tr            = new TableRow();
            td            = new TableCell();
            td.ColumnSpan = 2;

            // Add Body
            if (post.PostType == Posts.PostType.Post || post.PostType == Posts.PostType.Rating)
            {
                label          = new Label();
                label.CssClass = "normalTextSmall";
                label.Text     = Globals.FormatPostBody(post.Body);
                td.Controls.Add(label);
            }
            else if (post.PostType == Posts.PostType.Vote)
            {
                Vote vote = new Vote(post.PostID, post.Subject, post.Body);
                td.Controls.Add(vote);
                td.HorizontalAlign = HorizontalAlign.Center;
            }

            // Add row 2
            tr.Controls.Add(td);
            table.Controls.Add(tr);

            // Row 3 (Signature)
            tr            = new TableRow();
            td            = new TableCell();
            td.ColumnSpan = 2;

            label          = new Label();
            label.CssClass = "normalTextSmaller";

            if (postUser.Signature != "")
            {
                label.Text = Globals.FormatSignature(postUser.Signature);
            }
            td.Controls.Add(label);
            tr.Controls.Add(td);
            table.Controls.Add(tr);

            // Add whitespace
            tr        = new TableRow();
            td        = new TableCell();
            td.Height = 2;
            tr.Controls.Add(td);
            table.Controls.Add(tr);

            // Add buttons for user options
            tr            = new TableRow();
            td            = new TableCell();
            td.ColumnSpan = 2;

            // Add the reply button
            if (!post.IsLocked)
            {
                // Reply button
                HyperLink replyButton = new HyperLink();
                replyButton.Text        = "<img border=0 src=" + Globals.ApplicationVRoot + "/skins/" + Globals.Skin + "/images/newpost.gif" + ">";
                replyButton.NavigateUrl = Globals.UrlReplyToPost + post.PostID + "&mode=flat";
                td.Controls.Add(replyButton);
            }

            // Add the edit button
            if ((user != null) && (user.Username.ToLower() == post.Username.ToLower()) && (user.IsTrusted))
            {
                // Edit button
                HyperLink editButton = new HyperLink();
                editButton.Text        = "<img border=0 src=" + Globals.ApplicationVRoot + "/skins/" + Globals.Skin + "/images/editpost.gif" + ">";
                editButton.NavigateUrl = Globals.UrlUserEditPost + post.PostID + "&RedirectUrl=" + HttpContext.Current.Server.UrlEncode(Globals.UrlShowPost + postID);
                td.Controls.Add(editButton);
            }

            // Anything to add to the table control?
            if (td.Controls.Count > 0)
            {
                tr.Controls.Add(td);
                table.Controls.Add(tr);
            }

            // Is the current user a moderator?
            if ((user != null) && (user.IsModerator))
            {
                tr            = new TableRow();
                td            = new TableCell();
                td.ColumnSpan = 2;

                // Find the moderation menu
                ModerationMenu moderationMenu = new ModerationMenu();
                moderationMenu.PostID           = post.PostID;
                moderationMenu.ThreadID         = post.ThreadID;
                moderationMenu.UsernamePostedBy = post.Username;
                moderationMenu.SkinFilename     = "Moderation/Skin-ModeratePost.ascx";

                td.Controls.Add(moderationMenu);
                tr.Controls.Add(td);
                table.Controls.Add(tr);
            }

            postInfo.Controls.Add(table);
        }
Пример #41
0
        // GET: Rating/Create
        public ActionResult Create()
        {
            Rating rating = new Rating();

            return(View(rating));
        }
Пример #42
0
        public static Rating MenuRating(int?userId, int?itemId)

        {
            Console.OutputEncoding = Encoding.Unicode;
            Console.InputEncoding  = Encoding.Unicode;
            Rating rating = new Rating();

            rating.ItemId = itemId;
            rating.UserId = userId;
            int    ratingStars   = -1;
            string ratingTitle   = string.Empty;
            string ratingContent = string.Empty;

            try
            {
                Console.Write("#Nhập số sao: ");
                ratingStars = Convert.ToInt32(Console.ReadLine());
            }
            catch (System.Exception)
            {
            }
            if (ratingStars < 1 || ratingStars > 5)
            {
                do
                {
                    try
                    {
                        Console.WriteLine("Số sao phải từ 1 đến 5: ");
                        Console.Write("#Mời bạn nhập lại số sao: ");
                        ratingStars = Convert.ToInt32(Console.ReadLine());
                    }
                    catch (System.Exception)
                    {
                        continue;
                    }
                } while (ratingStars < 1 || ratingStars > 5);
            }
            try
            {
                Console.Write("#Nhập tiêu đề: ");
                ratingTitle = Console.ReadLine();
            }
            catch (System.Exception)
            {
            }
            if (ratingTitle.Length <= 0)
            {
                do
                {
                    try
                    {
                        Console.WriteLine("Bạn nhập sai");
                        Console.Write("#Mời bạn nhập lại tiêu đề: ");
                        ratingTitle = Console.ReadLine();
                    }
                    catch (System.Exception)
                    {
                        continue;
                    }
                } while (ratingTitle.Length <= 0);
            }

            try
            {
                Console.Write("#Nhập nội dung: ");
                ratingContent = Console.ReadLine();
            }
            catch (System.Exception)
            {
            }
            if (ratingContent.Length <= 0)
            {
                do
                {
                    try
                    {
                        Console.WriteLine("Bạn nhập sai");
                        Console.Write("#Mời bạn nhập lại nội dung: ");
                        ratingContent = Console.ReadLine();
                    }
                    catch (System.Exception)
                    {
                    }
                } while (ratingContent.Length <= 0);
            }

            rating.RatingStars   = ratingStars;
            rating.RatingTitle   = ratingTitle;
            rating.RatingContent = ratingContent;

            rating.RatingDate = DateTime.Now;
            return(rating);
        }
Пример #43
0
 public AgeRating(PersonAge age, Rating rating)
 {
     Age    = age ?? throw new ArgumentNullException(nameof(age));
     Rating = rating ?? throw new ArgumentNullException(nameof(rating));
 }
Пример #44
0
 public UserBuilder WithRating(Rating rating)
 {
     _rating = rating;
     return(this);
 }
Пример #45
0
 public Review(string movieName, Rating rating = Rating.Three, string reviewerName = "Anonymous")
 {
     MovieName    = movieName;
     Rating       = rating;
     ReviewerName = reviewerName;
 }
Пример #46
0
        public static void Initialize(MovieDatabaseContext context)
        {
            context.Database.EnsureCreated();

            #region Populate Ratings

            if (context.Ratings.Any())
            {
                return;
            }

            var ratings = new Rating[]
            {
                new Rating {
                    Name = "G",
                },
                new Rating {
                    Name = "PG"
                },
                new Rating {
                    Name = "PG-13"
                },
                new Rating {
                    Name = "R"
                },
                new Rating {
                    Name = "NC-17"
                }
            };
            foreach (Rating r in ratings)
            {
                context.Ratings.Add(r);
            }

            context.SaveChanges();

            #endregion

            #region Populate Genres

            var genres = new Genre[]
            {
                new Genre {
                    Name = "Action"
                },
                new Genre {
                    Name = "Adventure"
                },
                new Genre {
                    Name = "Comedy"
                },
                new Genre {
                    Name = "Crime"
                },
                new Genre {
                    Name = "Drama"
                },
                new Genre {
                    Name = "Fantasy"
                },
                new Genre {
                    Name = "Historical"
                },
                new Genre {
                    Name = "Horror"
                },
                new Genre {
                    Name = "Mystery"
                },
                new Genre {
                    Name = "Political"
                },
                new Genre {
                    Name = "Romance"
                },
                new Genre {
                    Name = "Science fiction"
                },
                new Genre {
                    Name = "Thriller"
                },
                new Genre {
                    Name = "Western"
                }
            };
            foreach (Genre g in genres)
            {
                context.Genres.Add(g);
            }

            context.SaveChanges();

            #endregion

            #region Populate Actors

            var actors = new Actor[]
            {
                new Actor {
                    FirstName = "Karen", MiddleName = "Sheila", LastName = "Gillan", BirthDate = new DateTime(1987, 9, 28), City = "Inverness", Country = "Scotland", Region = "UK", DeceasedDate = null
                },
                new Actor {
                    FirstName = "Cristin", MiddleName = "", LastName = "Milioti", BirthDate = new DateTime(1985, 8, 16), City = "Cherry Hill", Country = "New Jersey", Region = "USA", DeceasedDate = null
                },
                new Actor {
                    FirstName = "Ana", MiddleName = "Celia ", LastName = "de Armas", BirthDate = new DateTime(1988, 4, 30), City = "Havana", Country = "Cuba", Region = "", DeceasedDate = null
                },
                new Actor {
                    FirstName = "Daisy", MiddleName = "Jazz Isobel", LastName = "Ridley", BirthDate = new DateTime(1992, 4, 10), City = "London", Country = "England", Region = "UK", DeceasedDate = null
                },
                new Actor {
                    FirstName = "Jesse", MiddleName = "", LastName = "Plemons", BirthDate = new DateTime(1988, 4, 2), City = "Dallas", Country = "Texas", Region = "USA", DeceasedDate = null
                },
                new Actor {
                    FirstName = "Noomi", MiddleName = "", LastName = "Rapace", BirthDate = new DateTime(1979, 12, 28), City = "Hudiksvall, Gävleborgs län", Country = "Sweden", Region = "", DeceasedDate = null
                },
                new Actor {
                    FirstName = "Joel", MiddleName = "", LastName = "Edgerton", BirthDate = new DateTime(1974, 6, 23), City = "Blacktown", Country = "New South Wales", Region = "Australia", DeceasedDate = null
                },
                new Actor {
                    FirstName = "Tom", MiddleName = "", LastName = "Hardy", BirthDate = new DateTime(1977, 9, 15), City = "Hammersmith, London", Country = "England", Region = "UK", DeceasedDate = null
                },
                new Actor {
                    FirstName = "Adam", MiddleName = "Douglas", LastName = "Driver", BirthDate = new DateTime(1983, 11, 19), City = "San Diego", Country = "California", Region = "USA", DeceasedDate = null
                },
                new Actor {
                    FirstName = "Chris", MiddleName = "", LastName = "Zylka", BirthDate = new DateTime(1985, 5, 9), City = "Warren", Country = "Ohio", Region = "USA", DeceasedDate = null
                },
                new Actor {
                    FirstName = "Lucy", MiddleName = "Elizabeth", LastName = "Fry", BirthDate = new DateTime(1992, 3, 13), City = "Wooloowin", Country = "Brisbane", Region = "Australia", DeceasedDate = null
                },
                new Actor {
                    FirstName = "Rebecca", MiddleName = "Louisa Ferguson", LastName = "Sundström", BirthDate = new DateTime(1983, 10, 19), City = "Stockholm", Country = "Sweden", Region = "", DeceasedDate = null
                },
                new Actor {
                    FirstName = "Cillian", MiddleName = "", LastName = "Murphy", BirthDate = new DateTime(1976, 5, 25), City = "Douglas", Country = "Cork", Region = "Ireland", DeceasedDate = null
                },
                new Actor {
                    FirstName = "Claire", MiddleName = "Elizabeth", LastName = "Foy", BirthDate = new DateTime(1984, 4, 16), City = "Stockport", Country = "England", Region = "UK", DeceasedDate = null
                },
                new Actor {
                    FirstName = "Alexandra", MiddleName = "Anna", LastName = "Daddario", BirthDate = new DateTime(1986, 3, 16), City = "New York City", Country = "New York", Region = "USA", DeceasedDate = null
                },
                new Actor {
                    FirstName = "Gal", MiddleName = "", LastName = "Gadot", BirthDate = new DateTime(1985, 4, 30), City = " Rosh Ha\'ayin", Country = "Israel", Region = "", DeceasedDate = null
                },
                new Actor {
                    FirstName = "Emilia", MiddleName = "", LastName = "Clarke", BirthDate = new DateTime(1986, 10, 23), City = "London", Country = "England", Region = "UK", DeceasedDate = null
                },
                new Actor {
                    FirstName = "Bill", MiddleName = "", LastName = "Skarsgård", BirthDate = new DateTime(1990, 8, 9), City = "Vällingby", Country = "Sweden", Region = "", DeceasedDate = null
                },
            };
            foreach (Actor a in actors)
            {
                context.Actors.Add(a);
            }

            context.SaveChanges();

            #endregion
        }
Пример #47
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
            [CosmosDB(
                 databaseName: "c8",
                 collectionName: "Ratings",
                 ConnectionStringSetting = "CosmosDBConnection")]
            IAsyncCollector <Rating> ratings,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            Request data;

            try
            {
                data = JsonConvert.DeserializeObject <Request>(requestBody);
            }
            catch (Exception ex)
            {
                log.LogError(ex.Message);
                return(new BadRequestResult());
            }

            ApiRepository repository = new ApiRepository();
            User          user       = await repository.GetUserAsync(data.userId);

            Product product = await repository.GetProductAsync(data.productId);

            // Validation
            if (user == null || product == null)
            {
                return(new NotFoundResult());
            }
            if (data.rating < 0 || data.rating > 5)
            {
                return(new BadRequestResult());
            }

            Rating rating = new Rating()
            {
                id           = Guid.NewGuid(),
                userId       = data.userId,
                productId    = data.productId,
                locationName = data.locationName,
                rating       = data.rating,
                userNotes    = data.userNotes,
                timestamp    = DateTime.UtcNow
            };

            rating.sentimentScore = await GetScore(rating.id.ToString(), rating.userNotes);

            if (rating.sentimentScore < 0.3)
            {
                log.LogWarning("Bad sentiment score {0}, {1}, {2}", rating.sentimentScore, rating.userNotes, rating.id);
            }

            // Save to db
            await ratings.AddAsync(rating);

            return(new JsonResult(rating));
        }
Пример #48
0
 /// <summary>
 /// Adds a Rating to the database.
 /// </summary>
 /// <param name="rating"></param>
 /// <returns></returns>
 public void AddRating(Rating rating)
 {
     _dbContext.Ratings.Add(rating);
     _dbContext.SaveChanges();
 }
Пример #49
0
        //handles user and global rating.
        public ActionResult Rating(int lampid, int ratingvalue)
        {
            LampBaeEntities1 db = new LampBaeEntities1();

            //instantiate new list for lamp id's
            List <Listing> LampDBList = new List <Listing>();

            //grab listing based on lampid provided
            Listing listing = (from p in db.Listings
                               where p.ID == lampid
                               select p).Single();

            if (listing.Rating == null)
            {
                listing.Rating = 0;
                listing.Rating = listing.Rating + ratingvalue;
            }
            else
            {
                //global rating
                listing.Rating = listing.Rating + ratingvalue;
            }


            //user rating
            //instantiate new list for ratings
            List <Rating> RatingList = (from p in db.Ratings
                                        where p.RatingID != 0
                                        select p).ToList();

            Rating ratingrecord = new Rating();

            ratingrecord = null;

            // try to find a lamp with the lamp id/user id combo
            try
            {
                ratingrecord = (from m in db.Ratings
                                where m.ItemID == lampid &&
                                m.UserID == User.Identity.Name
                                select m).Single();
            }
            catch (Exception e)
            { }

            // if the record does not exist, then assign values, instantiate object and add the record.
            if (ratingrecord == null)
            {
                Rating rating = new Rating();

                rating.ItemID  = lampid;
                rating.UserID  = User.Identity.Name;
                rating.Rating1 = ratingvalue;
                new Rating {
                    ItemID = lampid, UserID = User.Identity.Name, Rating1 = ratingvalue
                };
                db.Ratings.Add(rating);
                db.SaveChanges();
            }

            // else, if a record exists, then increment or decrement the rating
            else
            {
                ratingrecord.Rating1 = ratingrecord.Rating1 + ratingvalue;
            }
            db.SaveChanges();
            return(RedirectToAction("Lamps"));
        }
Пример #50
0
 public List <RatingSubject> Get([FromQuery] string studnumber, string paspnumber)
 {
     return(Rating.GetRating(studnumber, paspnumber));
 }
Пример #51
0
 public void AddNewRating(Film film, ApplicationUser user, int value)
 {
     var newRating = new Rating { Film = film, User = user, Value = value };
     _unitOfWork.Ratings.Add(newRating);
 }
Пример #52
0
        public async Task CreateAsync(Rating rating)
        {
            await _context.Ratings.AddAsync(DbRating.Create(rating));

            await _context.SaveChangesAsync();
        }
Пример #53
0
 public void Update(Rating rating)
 {
     _ratingDal.Update(rating);
 }
Пример #54
0
            }                                       //creating a Years of Service property of type integer

            public void SetRating(Rating rating)
            {
                this.rating = rating;  //assigns the method parameter rating to the Employee.rating variable
            }
Пример #55
0
 public static ProgressUpdate HasMilestoneProgressRatingAt(this ProgressUpdate update, int index, Rating rating)
 {
     update.MilestonesProgress.ElementAt(index).Rating.Should().Be(rating);
     return(update);
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="currentInfo"></param>
        /// <param name="post"></param>
        /// <param name="rating"></param>
        /// <returns></returns>
        public static ModuleRatingInfo addRating(ModuleRatingInfo currentInfo, Post post, Rating rating)
        {
            // If post is not null, add the post and rating to forums database.
            // Even if the post is empty, still add it.

            if (post != null)
            {
                post.PostType = Posts.PostType.Rating;
                post.ParentID = currentInfo.ThreadID;
                post.IsLocked = true;
                post          = Posts.AddPost(post);
                rating.PostID = post.PostID;
                Ratings.AddRating(rating);
            }

            // Calculate the new rating and construct a new ModuleRatingInfo
            // object to be returned.

            float newRating = 0;

            if (currentInfo.NumRatings == 0)
            {
                newRating = rating.Value;
            }
            else
            {
                newRating = (currentInfo.Rating * currentInfo.NumRatings + rating.Value) /
                            (currentInfo.NumRatings + 1);
            }

            ModuleRatingInfo newInfo = new ModuleRatingInfo();

            newInfo.ModuleID   = currentInfo.ModuleID;
            newInfo.ThreadID   = currentInfo.ThreadID;
            newInfo.Rating     = newRating;
            newInfo.NumRatings = currentInfo.NumRatings + 1;

            // Update the module rating in the module database.

            ModuleRatings.updateRating(newInfo);

            return(newInfo);
        }
Пример #57
0
        public IActionResult CreateRating(Rating rating)
        {
            RequestResult <Rating> result = this.userFeedbackService.CreateRating(rating);

            return(new JsonResult(result));
        }
        public async Task AddRating(Rating rating)
        {
            await context.Ratings.AddAsync(rating);

            context.SaveChanges();
        }
Пример #59
0
 /// <summary>
 ///    Getting the percent value of total
 /// </summary>
 /// <param name="rating">Rating value</param>
 /// <returns>the percent value</returns>
 public static string GetPercentStr(this Rating rating)
 {
     return(string.Format("{0} %", rating.GetPercent() * 100));
 }
Пример #60
0
        private static void AddNewDVD()
        {
            Console.Clear();

            Movie newMovie;

            Console.Write("Please enter the movie title: ");
            String title = Console.ReadLine();

            Console.Write("\r\nPlease enter the genre (Drama, Adventure, Family, Action, SciFi, Comedy, Animated, Thriller, Other): ");
            Genre genre;

            if (Enum.TryParse <Genre>(Console.ReadLine(), out genre))
            {
            }
            else
            {
                genre = Genre.Other;
            }

            Console.Write("\r\nPlease enter the rating (G, PG, M15+, MA15+): ");

            Rating rating     = Rating.G;
            bool   choiceMade = false;

            while (!choiceMade)
            {
                switch (Console.ReadLine())
                {
                case "G":
                    rating     = Rating.G;
                    choiceMade = true;
                    break;

                case "PG":
                    rating     = Rating.PG;
                    choiceMade = true;
                    break;

                case "M15":
                case "M15+":
                case "M":
                    rating     = Rating.M15;
                    choiceMade = true;
                    break;

                case "MA15":
                case "MA15+":
                case "MA":
                    rating     = Rating.MA15;
                    choiceMade = true;
                    break;

                default:
                    Console.WriteLine("Please enter a valid selection (1-4): ");
                    break;
                }
            }

            Console.Write("\r\nPlease enter the actors starring in this movie: ");
            String starring = Console.ReadLine();

            Console.Write("\r\nPlease enter the director: ");
            String director = Console.ReadLine();

            Console.Write("\r\nPlease enter the duration: ");
            String duration = Console.ReadLine();

            Console.Write("\r\nPlease enter the release date (dd/mm/yyyy): ");
            DateTime releaseDate = DateTime.MinValue;

            while (!DateTime.TryParseExact(Console.ReadLine(), "d/M/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out releaseDate))
            {
                Console.WriteLine("Please enter a valid date (dd/mm/yyyy): ");
            }

            Console.Write("\r\nPlease enter the quantity of DVD's: ");
            int quantity = 0;

            while (!int.TryParse(Console.ReadLine(), out quantity))
            {
                Console.WriteLine("Please enter a valid number: ");
            }

            newMovie = new Movie(title, genre, rating, starring, director, duration, releaseDate, quantity);

            MovieCollection.AddMovie(newMovie);

            Console.Clear();

            Console.WriteLine("{0} added to the system.\r\n" +
                              "Press enter to return to staff menu... ", title);

            while (Console.ReadKey().Key != ConsoleKey.Enter)
            {
            }
        }