Ejemplo n.º 1
0
        // get : api/Movies?type={current/all order by name etc}
        protected override string ProcessRequest()
        {
            JavaScriptSerializer json = new JavaScriptSerializer();
            try
            {
                SetConnectionString();

                var qpParams = HttpUtility.ParseQueryString(this.Request.RequestUri.Query);
                if (string.IsNullOrEmpty(qpParams["type"]))
                {
                    throw new ArgumentException("type is not present");
                }

                string type = qpParams["type"].ToString();

                var tableMgr = new TableManager();
                var movies = new List<MovieEntity>();

                if (type.ToLower() == "orderby")
                {
                    movies = tableMgr.GetSortedMoviesByName();
                }
                else if (type.ToLower() == "current")
                {
                    movies = tableMgr.GetCurrentMovies();
                }

                return json.Serialize(movies);
            }
            catch (Exception ex)
            {
               return  json.Serialize(new { Status = "Error", Message = ex.Message });
            }
        }
Ejemplo n.º 2
0
        // get : api/Actor?n={actor/actress/producer...etc name}
        protected override string ProcessRequest()
        {
            JavaScriptSerializer json = new JavaScriptSerializer();

            try
            {
                var tableMgr = new TableManager();

                // get query string parameters
                var qpParam = HttpUtility.ParseQueryString(this.Request.RequestUri.Query);

                if (string.IsNullOrEmpty(qpParam["n"]))
                {
                    throw new ArgumentException(Constants.API_EXC_SEARCH_TEXT_NOT_EXIST);
                }

                string actorName = qpParam["n"].ToString();

                // get movies by actor(roles like actor, actress, producer, director... etc)
                var movies = tableMgr.SearchMoviesByActor(actorName);

                // serialize movie list and return
                return json.Serialize(movies);
            }
            catch (Exception ex)
            {
                // if any error occured then return User friendly message with system error message
                return json.Serialize(new { Status = "Error", UserMessage = Constants.UM_WHILE_SEARCHING_MOVIES, ActualError = ex.Message });
            }
        }
Ejemplo n.º 3
0
        internal static string QueueScoreReview(string movieId, string reviewId)
        {
            const string APIHost = "http://127.0.0.1:8081/";
            string reviewText;
            var tableMgr = new TableManager();
            var review = tableMgr.GetReviewById(reviewId);
            if (review != null)
            {
                reviewText = review.Review;
            }
            else
            {
                return jsonSerializer.Value.Serialize(new { Status = "Error", UserMessage = "Unable to get the review", ActualError = "" });
            }

            try
            {
                //Execute exe file
                var callProcessReviewProc = new Process();
                callProcessReviewProc.StartInfo = new ProcessStartInfo();

                callProcessReviewProc.EnableRaisingEvents = false;
                callProcessReviewProc.StartInfo.FileName = "cmd.exe";

                string dirPath = @"e:\workspace";
                string cmdPath = Path.Combine(dirPath, @"Scorer\scorer", "runScorer.cmd");
                string filename = string.Format("{0}_{1}", movieId, reviewId);
                string reviewFilename = Path.Combine(Path.GetTempPath(), filename + ".txt");
                string logFilename = Path.Combine(Path.GetTempPath(), filename + ".log");
                string uploadLogsUrl = string.Format("{0}api/algorithmlog?id={1}&p={2}",
                    APIHost,
                    reviewId,
                    logFilename);
                File.WriteAllText(reviewFilename, reviewText);

                callProcessReviewProc.StartInfo.Arguments =
                    string.Format("/C {0} \"{1}\" \"{2}\" \"{3}\" \"{4}\" \"{5}\" \"{6}\" \"{7}\"",
                        cmdPath,
                        dirPath,
                        logFilename,
                        movieId,
                        reviewId,
                        reviewFilename,
                        APIHost,
                        uploadLogsUrl);

                callProcessReviewProc.StartInfo.UseShellExecute = true;
                callProcessReviewProc.Start();
                callProcessReviewProc.WaitForExit();

                Scorer.UploadAlgorithmRunLogs(logFilename, reviewId);
                Scorer.SetTagsForReview(reviewId, logFilename);

                return jsonSerializer.Value.Serialize(new { Status = "Ok", UserMessage = "Successfully launch exe file" });
            }
            catch (Exception ex)
            {
                return jsonSerializer.Value.Serialize(new { Status = "Error", UserMessage = "Issue with executing the scorer script", ActualError = ex.Message });
            }
        }
Ejemplo n.º 4
0
        // get : api/Search?q={searchText}
        protected override string ProcessRequest()
        {
            JavaScriptSerializer json = new JavaScriptSerializer();

            try
            {
                var tableMgr = new TableManager();

                // get query string parameters
                var qpParams = HttpUtility.ParseQueryString(this.Request.RequestUri.Query);

                if (string.IsNullOrEmpty(qpParams["q"]))
                {
                    throw new ArgumentException(Constants.API_EXC_SEARCH_TEXT_NOT_EXIST);
                }

                string searchText = qpParams["q"];

                searchText = string.IsNullOrEmpty(searchText) ? string.Empty : searchText.Replace(".", "");

                // get movies by search keyword
                var movie = tableMgr.SearchMovies(searchText);

                // serialize movie list and return
                return json.Serialize(movie);
            }
            catch (Exception ex)
            {
                // if any error occured then return User friendly message with sys  tem error message
                return json.Serialize(new { Status = "Error", UserMessage = Constants.UM_WHILE_SEARCHING_MOVIES, ActualError = ex.Message });
            }
        }
Ejemplo n.º 5
0
        // get : api/Trailer?n={movie's unique name}
        protected override string ProcessRequest()
        {
            JavaScriptSerializer json = new JavaScriptSerializer();

            try
            {
                var tableMgr = new TableManager();

                // get query string parameters
                var qpParams = HttpUtility.ParseQueryString(this.Request.RequestUri.Query);
                if (string.IsNullOrEmpty(qpParams["n"]))
                {
                    throw new ArgumentException(Constants.API_EXC_MOVIE_NAME_NOT_EXIST);
                }

                string movieUniqueName = qpParams["n"].ToString();

                //get movie object by movie's unique name
                var movie = tableMgr.GetMovieByUniqueName(movieUniqueName);

                if (movie != null)
                {
                    // if movie is not null then return trailer string (in json)
                    return movie.Trailers;
                }
            }
            catch (Exception ex)
            {
                // if any error occured then return User friendly message with system error message
                return json.Serialize(new { Status = "Error", UserMessage = Constants.UM_WHILE_SEARCHING_MOVIES_TRAILER, ActualError = ex.Message });
            }

            // if movie is null then return single object.
            return string.Empty;
        }
Ejemplo n.º 6
0
        public ActionResult AddMovie(MoviePostData data)
        {
            if (data == null || string.IsNullOrEmpty(data.Name) || string.IsNullOrEmpty(data.UniqueName))
            {
                return null;
            }

            try
            {
                var tableMgr = new TableManager();
                MovieEntity movie = data.GetMovieEntity();
                movie.RowKey = movie.MovieId;
                tableMgr.UpdateMovieById(movie);

                UpdateCache(movie);

                UpdateLuceneIndex(movie);
            }
            catch (Exception)
            {
                return null;
            }

            return null;
        }
Ejemplo n.º 7
0
        protected override string ProcessRequest()
        {
            try
            {
                string queryParameters = this.Request.RequestUri.Query;
                TableManager tm = new TableManager();
                if (queryParameters != null)
                {
                    var qpParams = HttpUtility.ParseQueryString(queryParameters);
                    string physicalPath = string.Empty;
                    string reviewId = string.Empty;

                    if (!string.IsNullOrEmpty(qpParams["p"]) && !string.IsNullOrEmpty(qpParams["id"]))
                    {
                        physicalPath = qpParams["p"].ToString().ToLower().Trim();
                        reviewId = qpParams["id"].ToString();
                        Scorer.UploadAlgorithmRunLogs(physicalPath, reviewId);
                    }
                    else
                    {
                        return "Empty parameters";
                    }
                }
            }
            catch
            {
                throw;
            }

            return "Ok";
        }
Ejemplo n.º 8
0
        // get : api/GenreMovies?q=artist-name&page={default 30}
        protected override string ProcessRequest()
        {
            int resultLimit = 30;
            string genre = string.Empty;

            // get query string parameters
            string queryParameters = this.Request.RequestUri.Query;
            if (queryParameters != null)
            {
                var qpParams = HttpUtility.ParseQueryString(queryParameters);

                if (!string.IsNullOrEmpty(qpParams["page"]))
                {
                    int.TryParse(qpParams["page"].ToString(), out resultLimit);
                }

                if (!string.IsNullOrEmpty(qpParams["type"]))
                {
                    genre = qpParams["type"].ToLower();
                }
            }

            try
            {
                var tableMgr = new TableManager();
                var moviesByName = tableMgr.GetGenrewiseMovies(genre);
                List<MovieEntity> movies = moviesByName.Take(resultLimit).ToList();
                return jsonSerializer.Value.Serialize(movies);
            }
            catch (Exception)
            {
                // if any error occured then return User friendly message with system error message
                return jsonError.Value;
            }
        }
Ejemplo n.º 9
0
        // get : api/twitter?start=0&page=20
        protected override string ProcessRequest()
        {
            int startIndex = 0;
            int pageSize = 20;
            string name = string.Empty;
            string tweetType = string.Empty;

            // get query string parameters
            string queryParameters = this.Request.RequestUri.Query;
            if (!string.IsNullOrWhiteSpace(queryParameters))
            {
                var qpParams = HttpUtility.ParseQueryString(queryParameters);

                if (!string.IsNullOrEmpty(qpParams["start"]))
                {
                    int.TryParse(qpParams["start"].ToString(), out startIndex);
                }

                if (!string.IsNullOrEmpty(qpParams["page"]))
                {
                    int.TryParse(qpParams["page"].ToString(), out pageSize);
                }
                if (!string.IsNullOrEmpty(qpParams["type"]))
                {
                    tweetType = qpParams["type"].ToString().ToLower();
                }
                if (!string.IsNullOrEmpty(qpParams["name"]))
                {
                    name = qpParams["name"].ToString().ToLower();
                }
            }

            try
            {
                var tableMgr = new TableManager();
                IEnumerable<TwitterEntity> tweets = null;
                if (string.IsNullOrEmpty(tweetType))
                {
                    tweets = tableMgr.GetRecentTweets(startIndex, pageSize);
                }
                else
                {
                    tweets = tableMgr.GetRecentTweets(tweetType, name, startIndex, pageSize);
                }

                return jsonSerializer.Value.Serialize(tweets);
            }
            catch (Exception ex)
            {
                // if any error occured then return User friendly message with system error message
                return jsonSerializer.Value.Serialize(
                  new
                  {
                      Status = "Error",
                      UserMessage = "Unable to get tweets",
                      ActualError = ex.Message
                  });
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Entry point for the crawler. Pass the URL from source file (XML)
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public MovieEntity Crawl(string url)
        {
            MovieEntity movie = new MovieEntity();
            TableManager tableMgr = new TableManager();
            thumbnailPath = string.Empty;

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    #region Get Movie Page Content
                    Stream receiveStream = response.GetResponseStream();
                    StreamReader readStream = null;
                    if (response.CharacterSet == null)
                        readStream = new StreamReader(receiveStream);
                    else
                        readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));

                    moviePageContent = readStream.ReadToEnd();

                    response.Close();
                    readStream.Close();
                    #endregion

                    movie = PopulateMovieDetails(moviePageContent);
                    bool crawlPosters = true;

                    TableManager tblMgr = new TableManager();

                    MovieEntity me = tblMgr.GetMovieByUniqueName(movie.UniqueName);
                    if (me != null && !string.IsNullOrEmpty(me.RowKey))
                    {
                        movie.RowKey = me.RowKey;
                        movie.MovieId = me.MovieId;
                        movie.Popularity = Util.DEFAULT_POPULARITY;
                        movie.Posters = me.Posters;
                        movie.Songs = me.Songs;
                        movie.Trailers = me.Trailers;
                        movie.State = me.State;
                        crawlPosters = false;
                    }

                    PopulateMovieDetails(ref movie, url, crawlPosters);
                    return movie;
                    ////tableMgr.UpdateMovieById(movie);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("An error occurred while populating the movie details. Url = " + url + ". Error=" + ex.Message);
            }

            return movie;
        }
Ejemplo n.º 11
0
        public void CrawlArtists(List<Cast> castItems)
        {
            if (castItems == null)
            {
                return;
            }

            try
            {
                string artistPageContent = string.Empty;

                TableManager tblMgr = new TableManager();
                List<ArtistEntity> aeList = new List<ArtistEntity>();

                foreach (Cast cast in castItems)
                {
                    if (string.IsNullOrEmpty(cast.link)) continue;

                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(cast.link);
                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    {
                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            #region Get Artist Page Content
                            using (Stream receiveStream = response.GetResponseStream())
                            {
                                using (StreamReader readStream =
                                    response.CharacterSet == null ?
                                        new StreamReader(receiveStream)
                                        : new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet)))
                                {
                                    artistPageContent = readStream.ReadToEnd();
                                }
                            }
                            #endregion
                        }
                    }

                    ArtistEntity artist = PopulateArtistsDetails(artistPageContent, cast.link);
                    aeList.Add(artist);
                }

                //tblMgr.UpdateArtistItemById(aeList);

                foreach (ArtistEntity obj in aeList)
                {
                    tblMgr.UpdateArtistById(obj);
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
        }
Ejemplo n.º 12
0
        private void GetNews(string blobXmlFilePath = "")
        {
            try
            {
                XmlDocument xdoc = new XmlDocument();
                string newsXml = string.Empty;

                if (blobXmlFilePath == "")
                {
                    string basePath = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["MovieList"]);
                    string filePath = Path.Combine(basePath, "News.xml");
                    xdoc.Load(filePath);
                }
                else
                {
                    xdoc.Load(blobXmlFilePath);
                }

                var items = xdoc.SelectNodes("News/Link");
                if (items != null)
                {
                    foreach (XmlNode item in items)
                    {
                        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(item.InnerText);
                        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            #region Get News Content
                            Stream receiveStream = response.GetResponseStream();
                            StreamReader readStream = null;
                            if (response.CharacterSet == null)
                                readStream = new StreamReader(receiveStream);
                            else
                                readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));

                            newsXml = readStream.ReadToEnd();
                            List<NewsEntity> news = ParseNewsItems(newsXml, item.Attributes["type"].Value);
                            TableManager tblMgr = new TableManager();
                            tblMgr.UpdateNewsById(news);
                            response.Close();
                            readStream.Close();
                            #endregion
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
        }
Ejemplo n.º 13
0
        // get : api/Movies?type={current/all (default)}&resultlimit={default 100}
        protected override string ProcessRequest()
        {
            string type = "all";
            int resultLimit = 15;

            // get query string parameters
            string queryParameters = this.Request.RequestUri.Query;
            if (queryParameters != null)
            {
                var qpParams = HttpUtility.ParseQueryString(queryParameters);

                if (!string.IsNullOrEmpty(qpParams["type"]))
                {
                    type = qpParams["type"].ToString().ToLower();
                }

                if (!string.IsNullOrEmpty(qpParams["resultlimit"]))
                {
                    int.TryParse(qpParams["resultlimit"].ToString(), out resultLimit);
                }
            }

            try
            {
                var tableMgr = new TableManager();

                var moviesByName =
                    (type == "all") ?
                        tableMgr.GetSortedMoviesByName() :
                        (type == "current") ?
                            tableMgr.GetCurrentMovies() :
                            (type == "upcoming") ?
                                tableMgr.GetUpcomingMovies() :
                                    Enumerable.Empty<MovieEntity>();

                List<MovieEntity> movies = moviesByName.Take(resultLimit).ToList();

                // serialize movieList object and return.
                return jsonSerializer.Value.Serialize(movies);
            }
            catch (Exception ex)
            {
                // if any error occured then return User friendly message with system error message
                return jsonSerializer.Value.Serialize(
                   new
                   {
                       Status = "Error",
                       UserMessage = "Unable to get " + type + " movies",
                       ActualError = ex.Message
                   });
            }
        }
Ejemplo n.º 14
0
        public JsonResult AutoCompleteCountry(string term)
        {
            SetConnectionString();

            var tableMgr = new TableManager();
            var movie = tableMgr.SearchMovies(term);

            var users = (from u in movie
                         where u.Name.ToLower().Contains(term.ToLower())
                         select u.Name).Distinct().ToArray();

            return Json(users, JsonRequestBehavior.AllowGet);
        }
Ejemplo n.º 15
0
        //get api/AllSongs?q={searchText}
        protected override string ProcessRequest()
        {
            JavaScriptSerializer json = new JavaScriptSerializer();

            try
            {
                var tableMgr = new TableManager();

                // get query string parameters
                var qpParams = HttpUtility.ParseQueryString(this.Request.RequestUri.Query);
                if (string.IsNullOrEmpty(qpParams["q"]))
                {
                    throw new ArgumentException(Constants.API_EXC_SEARCH_TEXT_NOT_EXIST);
                }

                string searchSong = qpParams["q"];

                //get movie list based on song's title
                var movies = tableMgr.SearchSongs(searchSong);  //Collection of movie

                List<Songs> movieSongs = new List<Songs>();

                if (movies != null)
                {
                    // if movie list not null then get each movie's song
                    foreach (var movie in movies)
                    {
                        // deserialize movie songs
                        List<Songs> songs = json.Deserialize(movie.Songs, typeof(Songs)) as List<Songs>;

                        if (songs != null)
                        {
                            foreach (var song in songs)
                            {
                                // add song object to movie songs list
                                movieSongs.Add(song);
                            }
                        }
                    }
                }

                // serialize songs list and then return.
                return json.Serialize(movieSongs);
            }
            catch (Exception ex)
            {
                // if any error occured then return User friendly message with system error message
                return json.Serialize(new { Status = "Error", UserMessage = Constants.UM_WHILE_SEARCHING_SONGS, ActualError = ex.Message });
            }
        }
Ejemplo n.º 16
0
        // get : api/RateMovie?movieid=<mid>
        protected override string ProcessRequest()
        {
            // get query string parameters
            string queryParameters = this.Request.RequestUri.Query;
            if (queryParameters != null)
            {
                var qpParams = HttpUtility.ParseQueryString(queryParameters);

                string movieId = qpParams["movieid"];

                if (!string.IsNullOrEmpty(movieId))
                {
                    var tableMgr = new TableManager();
                    var movie = tableMgr.GetMovieById(movieId);
                    if (movie != null)
                    {
                        // Reset movie score
                        movie.MyScore = "0";
                        movie.Rating = "0";
                        tableMgr.UpdateMovieById(movie);

                        IDictionary<string, ReviewEntity> reviewEntities = tableMgr.GetReviewsByMovieId(movieId);
                        foreach (var pair in reviewEntities)
                        {
                            // Add code here
                            var response = Scorer.QueueScoreReview(movieId, pair.Value.ReviewId);
                            if (response.Contains("\"Error\""))
                            {
                                // There was an error - communicate this to user
                            }
                        }

                        return jsonSerializer.Value.Serialize(new { Status = "Error", UserMessage = "Queued rating reviews for this movie", ActualError = "" });
                    }
                    else
                    {
                        return jsonSerializer.Value.Serialize(new { Status = "Error", UserMessage = "Unable to find the movie", ActualError = "" });
                    }
                }
                else
                {
                    return jsonSerializer.Value.Serialize(new { Status = "Error", UserMessage = "Pass in movie ID", ActualError = "" });
                }
            }
            else
            {
                return jsonSerializer.Value.Serialize(new { Status = "Error", UserMessage = "Pass in movie ID", ActualError = "" });
            }
        }
Ejemplo n.º 17
0
        //Give the all unique actor name.
        protected override string ProcessRequest()
        {
            JavaScriptSerializer json = new JavaScriptSerializer();
            try
            {
                var tblMgr = new TableManager();

                //var movies = tblMgr.GetAllMovies();
                 var qpParam = HttpUtility.ParseQueryString(this.Request.RequestUri.Query);

                if (string.IsNullOrEmpty(qpParam["query"]))
                {
                    throw new ArgumentException(Constants.API_EXC_SEARCH_TEXT_NOT_EXIST);
                }

                string actorName = qpParam["query"].ToString();

                // get movies by actor(roles like actor, actress, producer, director... etc)
                var movies = tblMgr.SearchMoviesByActor(actorName);

                List<Object> allCast = new List<Object>();
                List<Cast> tempCast = new List<Cast>();
                int counter = 0;
                foreach (var movie in movies)
                {
                    List<Cast> castList = json.Deserialize(movie.Cast, typeof(List<Cast>)) as List<Cast>;
                    if (castList != null)
                    {

                        foreach (var cast in castList)
                        {
                            if (!tempCast.Exists(c => c.name == cast.name))
                            {
                                tempCast.Add(cast);
                                allCast.Add(new { id = ++counter, name = cast.name });
                            }
                        }

                    }
                }
                return json.Serialize(allCast);
            }
            catch (Exception ex)
            {
                return json.Serialize(new { staus = "Error", UserMessage = Constants.UM_WHILE_GETTING_CURRENT_MOVIES, ActualError = ex.Message });
                //throw new ArgumentException();
            }
        }
Ejemplo n.º 18
0
        public static string SetReviewer(string reviewerName, string affiliation)
        {
            string reviewerKey = string.Empty;
            try
            {
                #region Add Reviewer In DB
                TableManager tblMgr = new TableManager();
                ReviewerEntity reviewer = new ReviewerEntity();

                bool isReviewerAlreadyPresent = false;

                var reviewers = tblMgr.GetAllReviewer();

                for (int rid = 0; rid < reviewers.Keys.Count; rid++)
                {
                    string key = reviewers.ElementAt(rid).Key;
                    if (reviewers[key].ReviewerName.Trim() == reviewerName.Trim())
                    {
                        isReviewerAlreadyPresent = true;
                        reviewerKey = key;
                        break;
                    }
                }

                if (!isReviewerAlreadyPresent)
                {
                    reviewer.RowKey = reviewer.ReviewerId = Guid.NewGuid().ToString();
                    reviewer.ReviewerName = reviewerName.Trim();
                    reviewer.Affilation = affiliation.Trim();
                    reviewer.ReviewerImage = string.Empty;
                    tblMgr.UpdateReviewerById(reviewer);

                    reviewerKey = reviewer.ReviewerId;
                }
                #endregion
            }
            catch (Exception)
            {
            }

            return reviewerKey;
        }
Ejemplo n.º 19
0
        private static void UpdateCache(MovieEntity movie)
        {
            // Remove movie from Cache
            var movieKey = CacheConstants.MovieInfoJson + movie.UniqueName;
            var isPreviouslyCached = CacheManager.Exists(movieKey);
            CacheManager.Remove(movieKey);

            var tableMgr = new TableManager();

            // Cache if previously cached or movie is upcoming/current
            Task.Run(() =>
            {
                if (isPreviouslyCached || movie.State == "upcoming" || movie.State == "now playing")
                {
                    MovieInfoController.GetMovieInfo(movie.UniqueName);
                }
            });

            // Update more Cache
            Task.Run(() =>
            {
                // Update cache for AllMovies
                // Note: We are not updating CacheConstants.AllMovieEntitiesSortedByName here
                // because typically the name of the movie does not changes as often
                CacheManager.Remove(CacheConstants.AllMovieEntities);
                tableMgr.GetAllMovies();

                // Update current movies
                Task.Run(() =>
                {
                    CacheManager.Remove(CacheConstants.UpcomingMovieEntities);
                    var movies = tableMgr.GetCurrentMovies();
                });

                // Update upcoming movies
                Task.Run(() =>
                {
                    CacheManager.Remove(CacheConstants.NowPlayingMovieEntities);
                    var movies = tableMgr.GetUpcomingMovies();
                });
            });
        }
Ejemplo n.º 20
0
        // get : api/Search?search={searchText}
        //protected override string ProcessRequest()
        protected override string ProcessRequest()
        {
            JavaScriptSerializer json = new JavaScriptSerializer();

            var qpParams = HttpUtility.ParseQueryString(this.Request.RequestUri.Query);
            if (string.IsNullOrEmpty(qpParams["term"]))
            {
                throw new ArgumentException("search text is not present");
            }

            string searchText = qpParams["term"];

            var tableMgr = new TableManager();
            var movie = tableMgr.SearchMovies(searchText);

            var users = (from u in movie where u.Name.Contains(searchText)
                         select u.Name).Distinct().ToArray();

            return json.Serialize(users);
        }
Ejemplo n.º 21
0
        // get : api/ReviewRating?movieid=<mid>&reviewid=<rid>&rating=<rating>
        protected override string ProcessRequest()
        {
            // get query string parameters
            string queryParameters = this.Request.RequestUri.Query;

            try
            {
                if (queryParameters != null)
                {
                    var qpParams = HttpUtility.ParseQueryString(queryParameters);

                    if (!string.IsNullOrEmpty(qpParams["movieid"]) && !string.IsNullOrEmpty(qpParams["reviewid"]) && !string.IsNullOrEmpty(qpParams["rating"]))
                    {
                        string movieId = qpParams["movieid"].ToString();
                        string reviewId = qpParams["reviewid"].ToString();
                        string rating = qpParams["rating"].ToString();

                        var tableMgr = new TableManager();

                        bool result = tableMgr.UpdateReviewRating(reviewId, rating);
                        if (!result)
                        {
                            return jsonSerializer.Value.Serialize(new { Status = "Error", UserMessage = "Could not save the review rating", ActualError = "Unknown" });
                        }
                        else
                        {
                            // Update the movie rating
                        }

                        return jsonSerializer.Value.Serialize(new { Status = "Ok", UserMessage = "Successfully saved the rating" });
                    }
                }

            }
            catch (Exception ex)
            {
                return jsonSerializer.Value.Serialize(new { Status = "Error", UserMessage = "Unable to save the review rating", ActualError = ex.Message });
            }

            return jsonSerializer.Value.Serialize(new { Status = "Error", UserMessage = "Unable to save the review rating", ActualError = "Some of the parameters is empty" });
        }
Ejemplo n.º 22
0
        public string UserLogin(LoginProperties data)
        {
            if (data == null)
            {
                return MISSING;
            }

            try
            {
                JavaScriptSerializer json = new JavaScriptSerializer();
                UserEntity auth = new UserEntity();

                auth.UserName = data.UserName;
                auth.Password = GetHashPassword(data.Password);

                if (!string.IsNullOrEmpty(auth.UserName))
                {
                    TableManager tblMgr = new TableManager();
                    UserEntity user = tblMgr.GetUserByName(auth.UserName);

                    if (user != null && user.UserName == auth.UserName && user.Password == auth.Password)
                    {
                        return Login(user.UserId, user.UserType, user.FirstName, user.LastName, user.Email, user.Mobile, user.DateOfBirth, user.Gender, user.City, user.Favorite);
                    }
                    else
                    {
                        return INVALID;
                    }
                }
                else
                {
                    return MISSING;
                }
            }
            catch (Exception)
            {
                return ERROR;
            }
        }
Ejemplo n.º 23
0
        // get : api/Movies?type={current/all (default)}&resultlimit={default 100}
        protected override string ProcessRequest()
        {
            int resultLimit = 15;

            // get query string parameters
            string queryParameters = this.Request.RequestUri.Query;
            if (queryParameters != null)
            {
                var tableMgr = new TableManager();
                var qpParams = HttpUtility.ParseQueryString(queryParameters);

                string reviewerInitials = string.Empty;

                if (!string.IsNullOrEmpty(qpParams["q"]))
                {
                    reviewerInitials = qpParams["q"].ToString().ToLower();
                }

                var artistsByName = tableMgr.GetAllReviewer(reviewerInitials.ToLower()).Take(resultLimit).ToList().OrderBy(a => a.ReviewerName);
                return jsonSerializer.Value.Serialize(artistsByName);
            }

            return string.Empty;
        }
Ejemplo n.º 24
0
        public ActionResult UpdateArtist(ArtistPostData data)
        {
            if (data == null || string.IsNullOrEmpty(data.ArtistName) || string.IsNullOrEmpty(data.UniqueName))
            {
                return null;
            }

            try
            {
                var tableMgr = new TableManager();
                ArtistEntity artist = data.GetArtistEntity();
                //artist.RowKey = artist.ArtistId;
                // as per current records in our database.
                artist.RowKey = artist.UniqueName.ToLower();
                tableMgr.UpdateArtistById(artist);

            }
            catch (Exception)
            {
                return null;
            }

            return null;
        }
Ejemplo n.º 25
0
        public ActionResult Search(string q)
        {
            var connectionString = CloudConfigurationManager.GetSetting("StorageTableConnectionString");
            Trace.TraceInformation("Connection str read");
            ConnectionSettingsSingleton.Instance.StorageConnectionString = connectionString;

            if (string.IsNullOrWhiteSpace(q))
            {
                q = "testsample";
            }
            var tableMgr = new TableManager();
            var movie = tableMgr.GetMovieById(q);

            var resp = new StringBuilder();
            if (movie != null)
            {
                resp.Append("Movie Name : ");
                resp.Append(movie.Name);

                var reviews = movie.GetReviewIds();
                var reviewList = tableMgr.GetReviewsById(reviews);
                foreach (var reviewEntity in reviewList)
                {
                    resp.Append("\r\n With review -- ");
                    resp.Append(reviewEntity.Value.Review);
                }
            }
            else
            {
                resp.Append("No movie found");
            }

            ViewBag.Message = "You searched for " + q + "and the response you got was: " + resp;

            return View();
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Entry point for the crawler. Pass the URL from source file (XML)
        /// </summary>
        /// <param name="url"></param>
        public List<Songs> Crawl(string url)
        {
            MovieEntity movie = new MovieEntity();
            TableManager tableMgr = new TableManager();

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    #region Get Movie Page Content
                    Stream receiveStream = response.GetResponseStream();
                    StreamReader readStream = null;
                    if (response.CharacterSet == null)
                        readStream = new StreamReader(receiveStream);
                    else
                        readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));

                    songPageContent = readStream.ReadToEnd();

                    response.Close();
                    readStream.Close();
                    #endregion
                }

                return PopulateSongDetails(songPageContent);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("An error occurred while populating the movie details. Url = " + url + ". Error=" + ex.Message);
            }

            return null;
        }
Ejemplo n.º 27
0
        public string TestUpdate()
        {
            SetConnectionString();

            MovieEntity entity = new MovieEntity();
            var rand = new Random((int)DateTimeOffset.UtcNow.Ticks);

            entity.RowKey = entity.MovieId = Guid.NewGuid().ToString();
            entity.ReviewIds = string.Format("{0},{1}", Math.Abs(rand.Next()), Math.Abs(rand.Next()));
            entity.AggregateRating = Math.Abs(rand.Next(10)).ToString();
            entity.Directors = string.Format("Gabbar_{0}", rand.Next());
            entity.HotOrNot = (Math.Abs(rand.Next())%2) == 1 ? true : false;
            entity.MusicDirectors = string.Format("Rahman_{0}", Math.Abs(rand.Next()));
            entity.Name = string.Format("aashique {0}", rand.Next());
            entity.Producers = string.Format("sippy_{0}", rand.Next());
            entity.Actors = string.Format("sahruuk_{0}", rand.Next());

            var reviewIds = entity.GetReviewIds();
            var reviewList = new List<ReviewEntity>();
            foreach (var reviewId in reviewIds)
            {
                var reviewEntity = new ReviewEntity();
                reviewEntity.ReviewId = reviewEntity.RowKey = reviewId;
                reviewEntity.Review = string.Format("This is review number {0}", reviewId);
                reviewEntity.ReviewerName = string.Format("khan_{0}", rand.Next());
                reviewEntity.ReviewerRating = rand.Next(10);
                reviewEntity.SystemRating = rand.Next(10);

                reviewList.Add(reviewEntity);
            }

            var tableMgr = new TableManager();
            tableMgr.UpdateMovieById(entity);
            tableMgr.UpdateReviewsById(reviewList);

            return string.Format("Created movie id {0}", entity.MovieId);
        }
        protected override string ProcessRequest()
        {
            JavaScriptSerializer json = new JavaScriptSerializer();

            try
            {
                var tableMgr = new TableManager();

                // get query string parameters
                var qpParams = HttpUtility.ParseQueryString(this.Request.RequestUri.Query);
                if (string.IsNullOrEmpty(qpParams["d"]))
                {
                    //throw new ArgumentException(Constants.API_EXC_SEARCH_TEXT_NOT_EXIST);
                    return json.Serialize(new { Status = "Error", Message = Constants.API_EXC_SEARCH_TEXT_NOT_EXIST });
                }

                string userId = qpParams["u"];
                string cFavoriteId = qpParams["c"];
                string favorites = qpParams["d"];

                List<PopularOnMovieMirchiEntity> popularOnMovieMirchi = json.Deserialize(favorites, typeof(List<PopularOnMovieMirchiEntity>)) as List<PopularOnMovieMirchiEntity>;

                if (popularOnMovieMirchi != null)
                {
                    foreach (PopularOnMovieMirchiEntity objPopular in popularOnMovieMirchi)
                    {
                        PopularOnMovieMirchiEntity oldObjPopular = tableMgr.GetPopularOnMovieMirchiById(objPopular.Name + "=" + objPopular.Type);

                        // If the type = Actor - need to update the record
                        if (objPopular.Type.ToLower() == "actor")
                        {
                            // update the popularity count
                            ArtistEntity artist = tableMgr.GetArtist(objPopular.Name);

                            if (artist == null)
                                continue;

                            artist.Popularity = (int.Parse(artist.Popularity) + 1).ToString();
                            tableMgr.UpdateArtistById(artist);
                        }
                        else if (objPopular.Type.ToLower() == "critics")
                        {
                            // update the critics popularity count - We don't have column for storing popularity of critics
                            // Hence currently it is getting stored inside reviewer image. We are not storing reviewer image in this table
                            ReviewerEntity reviewer = tableMgr.GetReviewerById(objPopular.Name);

                            if (reviewer == null)
                                continue;

                            if (string.IsNullOrEmpty(reviewer.ReviewerImage))
                            {
                                reviewer.ReviewerImage = "0";
                            }

                            reviewer.ReviewerImage = (int.Parse(reviewer.ReviewerImage) + 1).ToString();
                            tableMgr.UpdateReviewerById(reviewer);
                        }
                        else if (objPopular.Type.ToLower() == "rate")
                        {
                            // update users table - save the site rating
                            UserEntity ue = tableMgr.GetUserById(userId);
                            if (ue == null)
                                continue;

                            ue.SiteFeedbackScore = objPopular.Name;
                            tableMgr.UpdateUserById(ue);
                        }

                        /*if (oldObjPopular == null && objPopular.Type.ToLower() != "rate")
                        {
                            objPopular.PopularOnMovieMirchiId = Guid.NewGuid().ToString();
                            objPopular.RowKey = objPopular.Name + "=" + objPopular.Type;
                            objPopular.Counter = 1;
                            objPopular.DateUpdated = DateTime.Now.ToString();

                            tableMgr.UpdatePopularOnMovieMirchiId(objPopular);
                        }
                        else if (objPopular.Type.ToLower() != "rate")
                        {
                            oldObjPopular.Counter = oldObjPopular.Counter + 1;
                            objPopular.DateUpdated = DateTime.Now.ToString();
                            tableMgr.UpdatePopularOnMovieMirchiId(oldObjPopular);
                        }*/
                    }
                }

                // User Id must be present - Fav id not present = create
                // USer id present - fav id present - update

                /*if (string.IsNullOrEmpty(userId) && string.IsNullOrEmpty(cFavoriteId))
                {
                    UserFavoriteEntity userFavorite = new UserFavoriteEntity();
                    userFavorite.RowKey = userFavorite.UserFavoriteId = Guid.NewGuid().ToString();
                    userFavorite.UserId = "";
                    userFavorite.Favorites = favorites;
                    userFavorite.DateCreated = DateTime.Now.ToString();

                    tableMgr.UpdateUserFavoriteById(userFavorite);

                    return json.Serialize(new { Status = "Ok", Message = "Set Cookie", FavoriteId = userFavorite.UserFavoriteId });
                }
                else */
                if (!string.IsNullOrEmpty(userId) && userId.ToLower() != "undefined" && !string.IsNullOrEmpty(cFavoriteId))
                {
                    UserFavoriteEntity userFavorite = tableMgr.GetUserFavoritesByUserId(userId);

                    if (userFavorite == null)
                    {
                        userFavorite = tableMgr.GetUserFavoriteById(cFavoriteId);

                        if (userFavorite != null)
                        {
                            userFavorite.UserId = userId;
                            userFavorite.Favorites = favorites;
                            userFavorite.DateCreated = DateTime.Now.ToString();
                            tableMgr.UpdateUserFavoriteById(userFavorite);
                        }
                    }
                    else
                    {
                        userFavorite.Favorites = favorites;
                        userFavorite.DateCreated = DateTime.Now.ToString();
                        tableMgr.UpdateUserFavoriteById(userFavorite);
                    }

                    return json.Serialize(new { Status = "Ok", Message = "Updated" });
                }
                else if (!string.IsNullOrEmpty(userId) && string.IsNullOrEmpty(cFavoriteId))
                {
                    UserFavoriteEntity userFavorite = tableMgr.GetUserFavoritesByUserId(userId);

                    if (userFavorite != null)
                    {
                        userFavorite.Favorites = favorites;
                        userFavorite.DateCreated = DateTime.Now.ToString();
                        tableMgr.UpdateUserFavoriteById(userFavorite);
                        return json.Serialize(new { Status = "Ok", Message = "Updated" });
                    }
                }

                return json.Serialize(new { Status = "Error", Message = "No Updated" });
            }
            catch (Exception ex)
            {
                // if any error occured then return User friendly message with system error message

                return json.Serialize(
                  new
                  {
                      Status = "Error",
                      UserMessage = "Unable to save your favorites. Please try again later.",
                      ActualError = ex.Message
                  });
            }
        }
Ejemplo n.º 29
0
        public void IndexSelectedReviews(ISet<string> reviewIds)
        {
            StandardAnalyzer analyzer = null;
            IndexWriter writer = null;
            try
            {
                analyzer = new StandardAnalyzer(Version.LUCENE_30);
                writer = new IndexWriter(_dirLocation, analyzer,
                                             IndexWriter.MaxFieldLength.UNLIMITED);

                var tableManager = new TableManager();

                var reviewList = tableManager.GetReviewsById(GenerateListFromSet(reviewIds));

                foreach (var id in reviewIds)
                {
                    if (reviewList.ContainsKey(id))
                    {
                        Trace.TraceInformation("Adding {0} to the index", id);

                        var reviewEntity = reviewList[id];

                        // delete entry if exists
                        var searchQuery = new TermQuery(new Term(Constants.Constants.Field_Id, id));
                        writer.DeleteDocuments(searchQuery);

                        // add to index again
                        var doc = new Document();
                        doc.Add(new Field(Constants.Constants.Field_Id, reviewEntity.ReviewId, Field.Store.YES,
                                          Field.Index.NOT_ANALYZED));

                        doc.Add(new Field(Constants.Constants.Field_EntityType, Constants.Constants.Field_EntityType_Reviews, Field.Store.YES,
                                          Field.Index.NOT_ANALYZED));
                        doc.Add(new Field(Constants.Constants.Field_ReviewerName, reviewEntity.ReviewerName, Field.Store.YES,
                                          Field.Index.ANALYZED));
                        doc.Add(new Field(Constants.Constants.Field_EntityType_ReviewText, reviewEntity.Review, Field.Store.YES, Field.Index.ANALYZED));

                        writer.AddDocument(doc);
                    }
                    else
                    {
                        Trace.TraceWarning("movie {0} not present in db", id);
                    }
                }

            }
            catch (Exception err)
            {
                Trace.TraceError("Failed to build index {0}", err);

            }
            finally
            {
                if (analyzer != null)
                    analyzer.Close();
                if (writer != null)
                    writer.Dispose();
            }
        }
Ejemplo n.º 30
0
        public void IndexSelectedMovies(ISet<string> movieIds)
        {
            StandardAnalyzer analyzer = null;
            IndexWriter writer = null;
            try
            {
                analyzer = new StandardAnalyzer(Version.LUCENE_30);
                writer = new IndexWriter(_dirLocation, analyzer,
                                             IndexWriter.MaxFieldLength.UNLIMITED);

                var tableManager = new TableManager();

                var movieList = tableManager.GetMoviesById(GenerateListFromSet(movieIds));

                foreach (var id in movieIds)
                {
                    if (movieList.ContainsKey(id))
                    {
                        Trace.TraceInformation("Adding {0} to the index", id);

                        var movieEntity = movieList[id];

                        // delete entry if exists
                        var searchQuery = new TermQuery(new Term(Constants.Constants.Field_Id, id));
                        writer.DeleteDocuments(searchQuery);

                        // add to index again
                        var doc = new Document();
                        doc.Add(new Field(Constants.Constants.Field_Id, movieEntity.MovieId, Field.Store.YES,
                                          Field.Index.NOT_ANALYZED));
                        doc.Add(new Field(Constants.Constants.Field_Name, movieEntity.Name, Field.Store.YES,
                                          Field.Index.NOT_ANALYZED));
                        doc.Add(new Field(Constants.Constants.Field_AltNames, movieEntity.AltNames, Field.Store.NO, Field.Index.ANALYZED));

                        doc.Add(new Field(Constants.Constants.Field_Actors, movieEntity.Posters, Field.Store.NO,
                                          Field.Index.ANALYZED));
                        doc.Add(new Field(Constants.Constants.Field_Directors, movieEntity.Rating, Field.Store.YES,
                                          Field.Index.ANALYZED));
                        doc.Add(new Field(Constants.Constants.Field_MusicDirectors, movieEntity.Cast,
                                          Field.Store.YES, Field.Index.ANALYZED));
                        doc.Add(new Field(Constants.Constants.Field_Name, movieEntity.Name, Field.Store.YES,
                                          Field.Index.ANALYZED));
                        doc.Add(new Field(Constants.Constants.Field_Producers, movieEntity.Synopsis, Field.Store.YES,
                                          Field.Index.ANALYZED));
                        doc.Add(new Field(Constants.Constants.Field_MovieSynopsis, movieEntity.Synopsis, Field.Store.YES,
                                          Field.Index.ANALYZED));

                        writer.AddDocument(doc);
                    }
                    else
                    {
                        Trace.TraceWarning("movie {0} not present in db", id);
                    }
                }

            }
            catch (Exception err)
            {
                Trace.TraceError("Failed to build index {0}", err);

            }
            finally
            {
                if (analyzer != null)
                    analyzer.Close();
                if (writer != null)
                    writer.Dispose();
            }
        }