/// <summary> /// Tests whether a <see cref="Geometry" /> is sequenced correctly. /// <see cref="LineString" />s are trivially sequenced. /// <see cref="MultiLineString" />s are checked for correct sequencing. /// Otherwise, <c>IsSequenced</c> is defined /// to be <c>true</c> for geometries that are not lineal. /// </summary> /// <param name="geom">The <see cref="Geometry" /> to test.</param> /// <returns> /// <c>true</c> if the <see cref="Geometry" /> is sequenced or is not lineal. /// </returns> public static bool IsSequenced(IGeometry geom) { if (!(geom is IMultiLineString)) return true; IMultiLineString mls = geom as IMultiLineString; // The nodes in all subgraphs which have been completely scanned ISet<ICoordinate> prevSubgraphNodes = new SortedSet<ICoordinate>(); ICoordinate lastNode = null; IList<ICoordinate> currNodes = new List<ICoordinate>(); for (int i = 0; i < mls.NumGeometries; i++) { ILineString line = (ILineString) mls.GetGeometryN(i); ICoordinate startNode = line.GetCoordinateN(0); ICoordinate endNode = line.GetCoordinateN(line.NumPoints - 1); /* * If this linestring is connected to a previous subgraph, geom is not sequenced */ if (prevSubgraphNodes.Contains(startNode)) return false; if (prevSubgraphNodes.Contains(endNode)) return false; if (lastNode != null && startNode != lastNode) { // start new connected sequence prevSubgraphNodes.AddAll(currNodes); currNodes.Clear(); } currNodes.Add(startNode); currNodes.Add(endNode); lastNode = endNode; } return true; }
/// <summary> /// Initializes a new instance of the QKeyedTable with specified column names and data matrix. /// </summary> public QKeyedTable(string[] columns, string[] keyColumns, Array data) { if (columns == null || columns.Length == 0) { throw new ArgumentException("Columns array cannot be null or 0-length"); } if (keyColumns == null || keyColumns.Length == 0) { throw new ArgumentException("Key columns array cannot be null or 0-length"); } if (data == null || data.Length == 0) { throw new ArgumentException("Data matrix cannot be null or 0-length"); } if (columns.Length != data.Length) { throw new ArgumentException("Columns array and data matrix cannot have different length"); } if (data.Cast<object>().Any(col => !col.GetType().IsArray)) { throw new ArgumentException("Non array column found in data matrix"); } if (keyColumns.Any(keyCol => !columns.Contains(keyCol))) { throw new ArgumentException("Non array column found in data matrix"); } var keyIndices = new SortedSet<int>(); for (int i = 0; i < columns.Length; i++) { if (keyColumns.Contains(columns[i])) { keyIndices.Add(i); } } var keyArrays = new object[keyIndices.Count]; var keyHeaders = new string[keyIndices.Count]; var dataArrays = new object[data.Length - keyIndices.Count]; var dataHeaders = new string[data.Length - keyIndices.Count]; int ki = 0; int di = 0; for (int i = 0; i < data.Length; i++) { if (keyIndices.Contains(i)) { keyHeaders[ki] = columns[i]; keyArrays[ki++] = data.GetValue(i); } else { dataHeaders[di] = columns[i]; dataArrays[di++] = data.GetValue(i); } } keys = new QTable(keyHeaders, keyArrays); values = new QTable(dataHeaders, dataArrays); }
/// <summary> /// Loads in games from a VDF node containing a list of games. /// Any games in the node not found in the game list will be added to the gamelist. /// If a game in the node has a tags subnode, the "favorite" field will be overwritten. /// If a game in the node has a category set, it will overwrite any categories in the gamelist. /// If a game in the node does NOT have a category set, the category in the gamelist will NOT be cleared. /// </summary> /// <param name="appsNode">Node containing the game nodes</param> /// <param name="ignore">Set of games to ignore</param> /// <returns>Number of games loaded</returns> private int IntegrateGamesFromVdf( VdfFileNode appsNode, SortedSet<int> ignore, bool ignoreDlc ) { int loadedGames = 0; Dictionary<string, VdfFileNode> gameNodeArray = appsNode.NodeArray; if( gameNodeArray != null ) { foreach( KeyValuePair<string, VdfFileNode> gameNodePair in gameNodeArray ) { int gameId; if( int.TryParse( gameNodePair.Key, out gameId ) ) { if( ( ignore != null && ignore.Contains( gameId ) ) || ( ignoreDlc && Program.GameDB.IsDlc( gameId ) ) ) { Program.Logger.Write( LoggerLevel.Verbose, GlobalStrings.GameData_SkippedProcessingGame, gameId ); continue; } if( gameNodePair.Value != null && gameNodePair.Value.ContainsKey( "tags" ) ) { SortedSet<Category> cats = new SortedSet<Category>(); loadedGames++; VdfFileNode tagsNode = gameNodePair.Value["tags"]; Dictionary<string, VdfFileNode> tagArray = tagsNode.NodeArray; if( tagArray != null ) { foreach( VdfFileNode tag in tagArray.Values ) { string tagName = tag.NodeString; if( tagName != null ) { Category c = GetCategory( tagName ); if( c != null ) cats.Add( c ); } } } bool hidden = false; if( gameNodePair.Value.ContainsKey( "hidden" ) ) { VdfFileNode hiddenNode = gameNodePair.Value["hidden"]; hidden = ( hiddenNode.NodeString == "1" || hiddenNode.NodeInt == 1 ); } // Add the game to the list if it doesn't exist already if( !Games.ContainsKey( gameId ) ) { GameInfo newGame = new GameInfo( gameId, string.Empty ); Games.Add( gameId, newGame ); newGame.Name = Program.GameDB.GetName( gameId ); Program.Logger.Write( LoggerLevel.Verbose, GlobalStrings.GameData_AddedNewGame, gameId, newGame.Name ); } if( cats.Count > 0 ) { this.SetGameCategories( gameId, cats, false ); } Games[gameId].Hidden = hidden; //TODO: Don't think SortedSet.ToString() does what I hope Program.Logger.Write( LoggerLevel.Verbose, GlobalStrings.GameData_ProcessedGame, gameId, ( cats.Count == 0 ) ? "~" : cats.ToString() ); } } } } return loadedGames; }
/// <summary> /// Adds a new game to the database, or updates an existing game with new information. /// </summary> /// <param name="appId">App ID to add or update</param> /// <param name="appName">Name of app to add, or update to</param> /// <param name="overWrite">If true, will overwrite any existing games. If false, will fail if the game already exists.</param> /// <param name="ignore">Set of games to ignore. Can be null. If the game is in this list, no action will be taken.</param> /// <param name="ignoreDlc">If true, ignore the game if it is marked as DLC in the loaded database.</param> /// <param name="isNew">If true, a new game was added. If false, an existing game was updated, or the operation failed.</param> /// <returns>True if the game was integrated, false otherwise.</returns> private bool IntegrateGame( int appId, string appName, bool overWrite, SortedSet<int> ignore, bool ignoreDlc, out bool isNew ) { isNew = false; if( ( ignore != null && ignore.Contains( appId ) ) || ( ignoreDlc && Program.GameDB.IsDlc( appId ) ) ) { Program.Logger.Write( LoggerLevel.Verbose, GlobalStrings.GameData_SkippedIntegratingGame, appId, appName ); return false; } isNew = SetGameName( appId, appName, overWrite ); Program.Logger.Write( LoggerLevel.Verbose, GlobalStrings.GameData_IntegratedGameIntoGameList, appId, appName, isNew ); return true; }
/// <summary> /// adds several items to a collection, then searches for items in that collection. The test is repeated 50 times to get a more consistent result /// </summary> /// <param name="collection"></param> /// <param name="numItemsToTest"></param> /// <returns></returns> static TimeSpan RunTestOneSortedSet(SortedSet<User> collection, int numItemsToTest) { Stopwatch timer = new Stopwatch(); timer.Start(); // perform the test 50 times: for (int counter = 0; counter < 50; counter++) { collection.Clear(); // add some random items Random rnd = new Random(); var sequence = from n in Enumerable.Range(1, numItemsToTest) select rnd.Next() * n; foreach (var item in sequence) collection.Add(new User(item, "family", "name")); // search for 1000 random items var sequence2 = from n in Enumerable.Range(1, 1000) select rnd.Next() * n; bool found = false; foreach (var item in sequence2) { // This method is an O(ln n) operation. found &= collection.Contains(new User(item, "family", "name")); } } timer.Stop(); return timer.Elapsed; }
public ActionResult GetAllVideosBasedOnEntitlements() { List<ShowLookUpObject> list = null; if (!GlobalConfig.IsSynapseEnabled) return Json(list, JsonRequestBehavior.AllowGet); var registDt = DateTime.Now; if (MyUtility.isUserLoggedIn()) { try { //var cache = DataCache.Cache; //string cacheKey = "MOBILEGAV:U:" + User.Identity.Name; //list = (List<ShowLookUpObject>)cache[cacheKey]; if (list == null) { list = new List<ShowLookUpObject>(); var context = new IPTV2Entities(); var UserId = new Guid(User.Identity.Name); var user = context.Users.FirstOrDefault(u => u.UserId == UserId); if (user != null) { SortedSet<Int32> ShowIds = new SortedSet<int>(); var service = context.Offerings.Find(GlobalConfig.offeringId).Services.FirstOrDefault(s => s.StatusId == GlobalConfig.Visible); foreach (var entitlement in user.Entitlements.Where(e => e.EndDate > registDt)) { if (entitlement is PackageEntitlement) { var packageEntitlement = (PackageEntitlement)entitlement; var pkgCat = context.PackageCategories.Where(p => p.PackageId == packageEntitlement.PackageId).Select(p => p.Category); var pkgCatSubCategories = pkgCat.Select(p => p.SubCategories); foreach (var categories in pkgCatSubCategories) { foreach (var category in categories) { var listOfIds = service.GetAllMobileShowIds(MyUtility.GetCurrentCountryCodeOrDefault(), category); var showList = context.CategoryClasses.Where(c => listOfIds.Contains(c.CategoryId) && c.StatusId == GlobalConfig.Visible); foreach (var show in showList) { if (show != null) { if (!(ShowIds.Contains(show.CategoryId))) { if (show.StartDate < registDt && show.EndDate > registDt) { if (show is Show) { if (!(show is LiveEvent)) { ShowLookUpObject data = new ShowLookUpObject(); data.Show = show.Description; data.ShowId = show.CategoryId; data.MainCategory = category.Description; data.MainCategoryId = category.CategoryId; data.ShowType = (show is Movie) ? "MOVIE" : "SHOW"; if (!(show is Movie)) list.Add(data); } } } } } } ShowIds.UnionWith(listOfIds); //For checking } } } else if (entitlement is ShowEntitlement) { var showEntitlement = (ShowEntitlement)entitlement; if (!(ShowIds.Contains(showEntitlement.CategoryId))) { if (!(showEntitlement.Show is LiveEvent)) { ShowLookUpObject data = new ShowLookUpObject(); var show = showEntitlement.Show; if (show != null) { if (show.StartDate < registDt && show.EndDate > registDt) { var CacheDuration = new TimeSpan(0, GlobalConfig.GetParentCategoriesCacheDuration, 0); var parentCategories = show.GetAllParentCategories(CacheDuration); var parent = context.CategoryClasses.Where(c => parentCategories.Contains(c.CategoryId) && c.StatusId == GlobalConfig.Visible && c is Category); data.Show = show.Description; data.ShowId = show.CategoryId; data.MainCategory = parent.First().Description; data.MainCategoryId = parent.First().CategoryId; data.ShowType = (show is Movie) ? "MOVIE" : "SHOW"; if (!(show is Movie)) ShowIds.Add(show.CategoryId); list.Add(data); } } } } } else if (entitlement is EpisodeEntitlement) { var episodeEntitlement = (EpisodeEntitlement)entitlement; var eCacheDuration = new TimeSpan(0, GlobalConfig.GetParentShowsForEpisodeCacheDuration, 0); var listOfShows = episodeEntitlement.Episode.GetParentShows(eCacheDuration); var parentShow = context.CategoryClasses.FirstOrDefault(c => listOfShows.Contains(c.CategoryId) && c.StatusId == GlobalConfig.Visible && c is Show); if (parentShow != null) { if (!(ShowIds.Contains(parentShow.CategoryId))) { if (!(parentShow is LiveEvent)) { if (parentShow.StartDate < registDt && parentShow.EndDate > registDt) { ShowLookUpObject data = new ShowLookUpObject(); var CacheDuration = new TimeSpan(0, GlobalConfig.GetParentCategoriesCacheDuration, 0); var parentCategories = ((Show)parentShow).GetAllParentCategories(CacheDuration); var parent = context.CategoryClasses.Where(c => parentCategories.Contains(c.CategoryId) && c.StatusId == GlobalConfig.Visible && c is Category); data.EpisodeId = episodeEntitlement.Episode.EpisodeId; data.EpisodeName = episodeEntitlement.Episode.Description + ", " + episodeEntitlement.Episode.DateAired.Value.ToString("MMMM d, yyyy"); data.Show = parentShow.Description; data.ShowId = parentShow.CategoryId; data.MainCategory = parent.First().Description; data.MainCategoryId = parent.First().CategoryId; data.ShowType = (parentShow is Movie) ? "MOVIE" : "SHOW"; if (!(parentShow is Movie)) { ShowIds.Add(parentShow.CategoryId); list.Add(data); } } } } } } } list = list.OrderBy(c => c.Show).ToList(); //cache.Put(cacheKey, list, DataCache.CacheDuration); } } } catch (Exception e) { MyUtility.LogException(e); } } return Json(list, JsonRequestBehavior.AllowGet); }
/// <summary> /// Adds or removes a track from the library collection /// </summary> /// <param name="sender">The sender of the event (the timer)</param> /// <param name="e">The event data</param> private void SourceModifiedDelay_Tick(object sender, EventArgs e) { sourceModifiedDelay.Stop(); Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate() { //ScanProgressBar.IsIndeterminate = true; //ScanProgress.Visibility = System.Windows.Visibility.Visible; Cursor = Cursors.AppStarting; })); ThreadStart GUIScanThread = delegate() { try { // copy the tracks into two lists SortedSet<string> trackPaths = new SortedSet<string>(); List<TrackData> tracksToAdd = new List<TrackData>(); SortedList<string, TrackData> tracksToRemove = new SortedList<string, TrackData>(); List<TrackData> tracksToUpdate = new List<TrackData>(); foreach (DictionaryEntry de in sourceModifiedTracks) { SourceModificationType modType = (SourceModificationType)de.Value; TrackData track = (TrackData)de.Key; if (modType == SourceModificationType.Added) tracksToAdd.Add(track); else if (modType == SourceModificationType.Removed) { if (!tracksToRemove.ContainsKey(track.Path)) tracksToRemove.Add(track.Path, track); } else tracksToUpdate.Add(de.Key as TrackData); } sourceModifiedTracks.Clear(); // copy the observable collections so we can work on them // outside the gui thread ObservableCollection<TrackData> files = new ObservableCollection<TrackData>(); foreach (TrackData t in SettingsManager.FileTracks) { files.Add(t); trackPaths.Add(t.Path); } // add tracks for (int j = 0; j < tracksToAdd.Count; j++) { TrackData track = tracksToAdd[j]; if (trackPaths.Contains(track.Path)) tracksToAdd.RemoveAt(j--); else files.Add(track); } // update source for file list U.L(LogLevel.Debug, "MAIN", "Adding tracks to GUI list"); //DateTime start = DateTime.Now; Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate() { SettingsManager.FileTracks = files; SettingsManager.FileTracks.CollectionChanged += new NotifyCollectionChangedEventHandler(LibraryTracks_CollectionChanged); if (FileTracks != null) FileTracks.ItemsSource = files; if (SettingsManager.CurrentSelectedNavigation == "Files") InfoPaneTracks.Text = String.Format(U.T("HeaderTracks"), SettingsManager.FileTracks.Count); //ScanProgressBar.IsIndeterminate = false; //ScanProgressBar.Value = 0; })); // remove tracks //int numTracks = tracksToRemove.Count + tracksToAdd.Count + tracksToUpdate.Count; //double progressDelta = 100.0 / numTracks; //if (Double.IsInfinity(progressDelta)) progressDelta = 0; //double progress = 0; //double removeDelta = progressDelta * tracksToRemove.Count; if (tracksToRemove.Count > 0) { // remove if current track for (int i = 0; i < tracksToRemove.Count; i++) { TrackData track = tracksToRemove.Values[i]; if (SettingsManager.CurrentTrack.Path == track.Path) SettingsManager.CurrentTrack = null; } //double lists = SettingsManager.Playlists.Count + 3; //double trackDelta = progressDelta / lists; //double listDelta = removeDelta / lists; double listDelta = 1; foreach (PlaylistData p in SettingsManager.Playlists) RemoveTracks(tracksToRemove, p.Tracks, listDelta); RemoveTracks(tracksToRemove, SettingsManager.QueueTracks, listDelta); RemoveTracks(tracksToRemove, SettingsManager.HistoryTracks, listDelta); RemoveTracks(tracksToRemove, SettingsManager.FileTracks, listDelta); } //progress = removeDelta; //if (showBar) // Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate() // { // ScanProgressBar.Value = progress; // })); // update tracks //U.L(LogLevel.Debug, "MAIN", "Updating tracks"); for (int j = 0; j < tracksToAdd.Count; j++) { TrackData track = tracksToAdd[j]; if (U.IsClosing) return; FilesystemManager.UpdateTrack(track, false); //if (showBar && j % 100 == 0) //{ // Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate() // { // ScanProgressBar.Value = progress; // })); //} //progress += progressDelta; } for (int j = 0; j < tracksToUpdate.Count; j++) { TrackData track = tracksToUpdate[j]; if (U.IsClosing) return; FilesystemManager.UpdateTrack(track, false); //if (j % 100 == 0) //{ // Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate() // { // ScanProgressBar.Value = progress; // })); //} //progress += progressDelta; } //TimeSpan ts = (DateTime.Now - start); //double time = Math.Round(ts.TotalMilliseconds / numTracks, 2); //U.L(LogLevel.Debug, "FILESYSTEM", String.Format("Scanning took {0} seconds, an average of {1} ms/track", Math.Round(ts.TotalSeconds, 2), time)); Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate() { Cursor = Cursors.Arrow; //ScanProgress.Visibility = System.Windows.Visibility.Collapsed; })); // call callbacks Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate() { foreach (KeyValuePair<ScannerCallback, object> pair in sourceModifiedCallbacks) { ScannerCallback callback = pair.Key; object callbackParams = pair.Value; if (callback != null) callback(callbackParams); } sourceModifiedCallbacks.Clear(); })); } catch (Exception exc) { U.L(LogLevel.Warning, "MAIN", "Error occured in meta scanner: " + exc.Message); U.L(LogLevel.Warning, "MAIN", "Restarting meta scanner."); SourceModifiedDelay_Tick(sender, e); } }; Thread gs_thread = new Thread(GUIScanThread); gs_thread.Name = "GUI scan updater"; gs_thread.IsBackground = true; gs_thread.Priority = ThreadPriority.Lowest; gs_thread.Start(); }
public void ViewAdd () { var set = new SortedSet<int> { 1, 3, 5, 7 }; var view = set.GetViewBetween (3, 5); Assert.IsTrue (view.Add (4)); Assert.IsTrue (view.Contains (4)); Assert.IsTrue (set.Contains (4)); Assert.IsFalse (view.Add (5)); }
public void TestFullRankingWithTwoGone() { var p = new Person(3, new Random()); var fr = p.FullRanking(new int[] { 1, 0 }).ToArray(); Assert.AreEqual(1, fr.Length, "Incorrect number came back"); CheckContiguous(fr.Select(c => c.ranking).ToArray(), 1); var s = new SortedSet<int>(fr.Select(c => c.candidate)); Assert.IsFalse(s.Contains(1), "candidate 1 should not be in there"); Assert.IsFalse(s.Contains(3), "candidate 3 should not be in there"); }
static void PerformDFS(ref string[,] honeyGrid, ref HashSet<string> Dict, ref HashSet<string> prefix, ref SortedSet<string> Found, ref bool[,] visited, int levels, int xc, int yc, StringBuilder word) { StringBuilder temp = new StringBuilder(); try { temp.Append(string.Copy(word.ToString())); temp.Append(honeyGrid[xc, yc]); if (prefix.Contains(temp.ToString())) { visited[xc, yc] = true; if (Dict.Contains(temp.ToString())) { if (!Found.Contains(temp.ToString())) //to prevent duplicate entries found in different paths... Found.Add(temp.ToString()); } if (xc - 1 >= 0 && honeyGrid[xc - 1, yc] != null && !visited[xc - 1, yc]) //can move up { PerformDFS(ref honeyGrid, ref Dict, ref prefix, ref Found, ref visited, levels, xc - 1, yc, temp); } if (xc - 1 >= 0 && (yc + 1 < 2 * levels - 1) && honeyGrid[xc - 1, yc + 1] != null && !visited[xc - 1, yc + 1]) //can move diagonally up { PerformDFS(ref honeyGrid, ref Dict, ref prefix, ref Found, ref visited, levels, xc - 1, yc + 1, temp); } if ((yc + 1 < 2 * levels - 1) && honeyGrid[xc, yc + 1] != null && !visited[xc, yc + 1]) //can move right { PerformDFS(ref honeyGrid, ref Dict, ref prefix, ref Found, ref visited, levels, xc, yc + 1, temp); } if ((xc + 1 < 2 * levels - 1) && honeyGrid[xc + 1, yc] != null && !visited[xc + 1, yc]) //can move down { PerformDFS(ref honeyGrid, ref Dict, ref prefix, ref Found, ref visited, levels, xc + 1, yc, temp); } if ((xc + 1 < 2 * levels - 1) && (yc - 1 >= 0) && honeyGrid[xc + 1, yc - 1] != null && !visited[xc + 1, yc - 1]) //can move diagonally down { PerformDFS(ref honeyGrid, ref Dict, ref prefix, ref Found, ref visited, levels, xc + 1, yc - 1, temp); } if (yc - 1 >= 0 && honeyGrid[xc, yc - 1] != null && !visited[xc, yc - 1]) //can move left { PerformDFS(ref honeyGrid, ref Dict, ref prefix, ref Found, ref visited, levels, xc, yc - 1, temp); } visited[xc, yc] = false; } } catch (Exception) { throw; } }
public ActionResult Details(string id, int? PackageOption, int? ProductOption) { var profiler = MiniProfiler.Current; #region if (!Request.Cookies.AllKeys.Contains("version")) if (!Request.Cookies.AllKeys.Contains("version")) { List<SubscriptionProductA> productList = null; try { #region if user is not loggedin if (!User.Identity.IsAuthenticated) { if (!String.IsNullOrEmpty(id)) { if (String.Compare(id, "mayweather-vs-pacquiao-may-3", true) == 0) { HttpCookie pacMayCookie = new HttpCookie("redirect3178"); pacMayCookie.Expires = DateTime.Now.AddDays(1); Response.Cookies.Add(pacMayCookie); id = GlobalConfig.PacMaySubscribeCategoryId.ToString(); } if (String.Compare(id, GlobalConfig.PacMaySubscribeCategoryId.ToString(), true) != 0) { TempData["LoginErrorMessage"] = "Please register or sign in to avail of this promo."; TempData["RedirectUrl"] = Request.Url.PathAndQuery; if (String.Compare(id, "lckbprea", true) == 0) { HttpCookie preBlackCookie = new HttpCookie("redirectlckbprea"); preBlackCookie.Expires = DateTime.Now.AddDays(1); Response.Cookies.Add(preBlackCookie); } else if (String.Compare(id, "Promo201410", true) == 0) { HttpCookie promo2014010 = new HttpCookie("promo2014cok"); promo2014010.Expires = DateTime.Now.AddDays(1); Response.Cookies.Add(promo2014010); } else if (String.Compare(id, "aintone", true) == 0) { HttpCookie preBlackCookie = new HttpCookie("redirectaintone"); preBlackCookie.Expires = DateTime.Now.AddDays(1); Response.Cookies.Add(preBlackCookie); } //check if id is integer try { int tempId = 0; if (Int32.TryParse(id, out tempId)) { TempData["LoginErrorMessage"] = "Please sign in to purchase this product."; TempData["RedirectUrl"] = Request.Url.PathAndQuery; if (Request.Browser.IsMobileDevice) return RedirectToAction("MobileSignin", "User", new { ReturnUrl = Server.UrlEncode(Request.Url.PathAndQuery) }); else return RedirectToAction("Login", "User", new { ReturnUrl = Server.UrlEncode(Request.Url.PathAndQuery) }); } } catch (Exception) { } if (Request.Browser.IsMobileDevice) return RedirectToAction("MobileSignin", "User"); else return RedirectToAction("Login", "User"); } } else { TempData["LoginErrorMessage"] = "Please register or sign in to subscribe."; TempData["RedirectUrl"] = Request.Url.PathAndQuery; if (Request.Browser.IsMobileDevice) return RedirectToAction("MobileSignin", "User"); else return RedirectToAction("Login", "User"); } } #endregion #region user authenticated flow else if (!String.IsNullOrEmpty(id)) if (String.Compare(id, "mayweather-vs-pacquiao-may-3", true) == 0) id = GlobalConfig.PacMaySubscribeCategoryId.ToString(); var context = new IPTV2Entities(); string ip = Request.IsLocal ? "78.95.139.99" : Request.GetUserHostAddressFromCloudflare(); if (GlobalConfig.isUAT && !String.IsNullOrEmpty(Request.QueryString["ip"])) ip = Request.QueryString["ip"].ToString(); var location = MyUtility.GetLocationBasedOnIpAddress(ip); var CountryCode = location.countryCode; //var CountryCode = MyUtility.GetCountryCodeViaIpAddressWithoutProxy(); User user = null; Guid? UserId = null; if (User.Identity.IsAuthenticated) { UserId = new Guid(User.Identity.Name); user = context.Users.FirstOrDefault(u => u.UserId == UserId); if (user != null) CountryCode = user.CountryCode; } var country = context.Countries.FirstOrDefault(c => String.Compare(c.Code, CountryCode, true) == 0); var premium = MyUtility.StringToIntList(GlobalConfig.PremiumProductIds); var lite = MyUtility.StringToIntList(GlobalConfig.LiteProductIds); var movie = MyUtility.StringToIntList(GlobalConfig.MovieProductIds); var litepromo = MyUtility.StringToIntList(GlobalConfig.LitePromoProductIds); var promo2014promo = MyUtility.StringToIntList(GlobalConfig.Promo2014ProductIds); var q22015promo = MyUtility.StringToIntList(GlobalConfig.Q22015ProductId); var productIds = premium;//productids var offering = context.Offerings.Find(GlobalConfig.offeringId); var service = offering.Services.FirstOrDefault(o => o.PackageId == GlobalConfig.serviceId); bool IsAlaCarteProduct = true; #region code for showing product based on id if (!String.IsNullOrEmpty(id)) { int pid; #region if id is integer if (int.TryParse(id, out pid)) // id is an integer, then it's a show, get ala carte only { var show = (Show)context.CategoryClasses.Find(pid); #region check user is blocked on IP by his email if (User.Identity.IsAuthenticated) { var allowedEmails = GlobalConfig.EmailsAllowedToBypassIPBlock.Split(','); var isEmailAllowed = allowedEmails.Contains(user.EMail.ToLower()); if (!isEmailAllowed) { if (!ContextHelper.IsCategoryViewableInUserCountry(show, CountryCode)) return RedirectToAction("Index", "Home"); string CountryCodeBasedOnIpAddress = MyUtility.GetCountryCodeViaIpAddressWithoutProxy(); if (!ContextHelper.IsCategoryViewableInUserCountry(show, CountryCodeBasedOnIpAddress)) return RedirectToAction("Index", "Home"); } } #endregion try { #region show parent categories based on show category id var ShowParentCategories = ContextHelper.GetShowParentCategories(show.CategoryId); if (!String.IsNullOrEmpty(ShowParentCategories)) { ViewBag.ShowParentCategories = ShowParentCategories; if (!MyUtility.IsWhiteListed(String.Empty)) { #region if not ip whitelisted var ids = MyUtility.StringToIntList(ShowParentCategories); var alaCarteIds = MyUtility.StringToIntList(GlobalConfig.UXAlaCarteParentCategoryIds); var DoCheckForGeoIPRestriction = ids.Intersect(alaCarteIds).Count() > 0; if (DoCheckForGeoIPRestriction) { var ipx = Request.IsLocal ? "221.121.187.253" : String.Empty; if (GlobalConfig.isUAT) ipx = Request["ip"]; if (!MyUtility.CheckIfCategoryIsAllowed(show.CategoryId, context, ipx)) { var ReturnCode = new TransactionReturnType() { StatusHeader = "Content Advisory", StatusMessage = "This content is currently not available in your area.", StatusMessage2 = "You may select from among the hundreds of shows and movies that are available on the site." }; TempData["ErrorMessage"] = ReturnCode; return RedirectToAction("Index", "Home"); } } #endregion } } #endregion } catch (Exception) { } productIds = show.GetPackageProductIds(offering, CountryCode, RightsType.Online);//* var showProductIds = show.GetShowProductIds(offering, CountryCode, RightsType.Online);//* if (showProductIds != null) productIds = productIds.Union(showProductIds);//* //Remove premium, lite & movie packages from list productIds = productIds.Except(premium).Except(lite).Except(movie).Except(litepromo); IsAlaCarteProduct = true; if (pid == GlobalConfig.PacMaySubscribeCategoryId) { ViewBag.IsPacMay = true; //add the additional product ids var additional_pacmay_productids = MyUtility.StringToIntList(GlobalConfig.PacMaySubscribeProductIds); productIds = productIds.Union(additional_pacmay_productids); TempData["IsPacPurchase"] = true; } } #endregion #region if id is not integer else // get packages only { #region if id is Lite if (String.Compare(id, "Lite", true) == 0) productIds = lite; #endregion #region if id is Movie else if (String.Compare(id, "Movie", true) == 0) productIds = movie; #endregion #region if id is LitePromo else if (String.Compare(id, "LitePromo", true) == 0) { var promo = context.Promos.FirstOrDefault(p => p.PromoId == GlobalConfig.LiteChurnersPromoId); if (promo != null) { var registDt = DateTime.Now; if (promo.StatusId == GlobalConfig.Visible && promo.StartDate < registDt && promo.EndDate > registDt) productIds = litepromo; // discounted lite product Ids } } #endregion #region if id is Promo201410 else if (String.Compare(id, "Promo201410", true) == 0) { var promo = context.Promos.FirstOrDefault(p => p.PromoId == GlobalConfig.Promo201410PromoId); if (promo != null) { var registDt = DateTime.Now; if (promo.StatusId == GlobalConfig.Visible && promo.StartDate < registDt && promo.EndDate > registDt) { ViewBag.IsPromo2014 = true; ViewBag.PreventAutoRenewalCheckboxFromUntick = true; productIds = promo2014promo; // discounted 3month premium //get amount of 3 month premium var premium1mo = context.Products.FirstOrDefault(p => p.ProductId == 1); if (premium1mo != null) ViewBag.Premium1MonthPrice = premium1mo.ProductPrices.FirstOrDefault(p => String.Compare(p.CurrencyCode, country.CurrencyCode, true) == 0); //check purchasetry try { var user_purchases = context.PurchaseItems.Where(p => promo2014promo.Contains(p.ProductId) && p.RecipientUserId == user.UserId); if (user_purchases != null) { var purchaseIds = user_purchases.Select(p => p.PurchaseId); var purchases = context.Purchases.Count(p => purchaseIds.Contains(p.PurchaseId) && p.Date > promo.StartDate && p.Date < promo.EndDate); if (purchases > 0) ViewBag.UserHasAvailedOfPromo201410 = true; } } catch (Exception) { } } } } #endregion #region if id is lckbprea else if (String.Compare(id, "lckbprea", true) == 0) { var registDt = DateTime.Now; var preBlackPromo = context.Promos.FirstOrDefault(p => p.PromoId == GlobalConfig.PreBlackPromoId && p.StatusId == GlobalConfig.Visible && p.StartDate < registDt && p.EndDate > registDt); if (preBlackPromo != null) { //productIds = MyUtility.StringToIntList(GlobalConfig.PreBlackPromoProductIds); var productIdsList = new List<Int32>(); var preBlackPromoIds = MyUtility.StringToIntList(GlobalConfig.PreBlackPromoProductIds).ToList(); var preBlackPurchaseItems = context.PurchaseItems.Where(p => preBlackPromoIds.Contains(p.ProductId) && p.RecipientUserId == user.UserId).Select(p => p.SubscriptionProduct); List<Int32> preBlackPurchaseItemsList = preBlackPurchaseItems.Select(p => p.Duration).ToList(); var sumDuration = preBlackPurchaseItemsList.Take(preBlackPurchaseItemsList.Count).Sum(); if (sumDuration > 11) { var ReturnCode = new TransactionReturnType() { StatusCode = (int)ErrorCodes.UnknownError, StatusMessage = "You have reached the maximum number of purchases for this product.", info = "pre-black", TransactionType = "Purchase" }; TempData["ErrorMessage"] = ReturnCode; return RedirectToAction("Index", "Home"); } if (sumDuration < 12) productIdsList.Add(preBlackPromoIds[0]); if (sumDuration < 9) productIdsList.Add(preBlackPromoIds[1]); if (sumDuration == 0) productIdsList.Add(preBlackPromoIds[2]); productIds = productIdsList; } } #endregion #region if id is atra else if (String.Compare(id, "atra", true) == 0) { var registDt = DateTime.Now; var productIdsList = new List<Int32>(); var projectBlackPromoIdsList = MyUtility.StringToIntList(GlobalConfig.ProjectBlackPromoIds); var projectBlackProductIdsList = MyUtility.StringToIntList(GlobalConfig.ProjectBlackProductIds).ToList(); var blackProjetPromo = context.Promos.FirstOrDefault(p => projectBlackPromoIdsList.Contains(p.PromoId) && p.StatusId == GlobalConfig.Visible && p.StartDate < registDt && p.EndDate > registDt); if (blackProjetPromo != null) { if (User.Identity.IsAuthenticated) { var userpromo = context.UserPromos.FirstOrDefault(u => u.UserId == UserId && projectBlackPromoIdsList.Contains(u.PromoId)); if (userpromo == null) { if (projectBlackProductIdsList.Count > 0) { productIdsList.Add(projectBlackProductIdsList[projectBlackProductIdsList.Count - 1]); productIds = productIdsList; ViewBag.isProjectBlack = true; var premium3mo = context.Products.FirstOrDefault(p => p.ProductId == 1); if (premium3mo != null) ViewBag.Premium1MonthPrice = premium3mo.ProductPrices.FirstOrDefault(p => String.Compare(p.CurrencyCode, country.CurrencyCode, true) == 0); } else { return RedirectToAction("Details", new { id = String.Empty }); } } else { var ReturnCode = new TransactionReturnType() { StatusCode = (int)ErrorCodes.UnknownError, StatusMessage = "You have already claimed this promo.", info = "black", TransactionType = "Purchase" }; TempData["ErrorMessage"] = ReturnCode; return RedirectToAction("Index", "Home"); } } } else { return RedirectToAction("Details", new { id = String.Empty }); } } #endregion #region id id is aintone else if (String.Compare(id, "aintone", true) == 0) { var promo = context.Promos.FirstOrDefault(p => p.PromoId == GlobalConfig.Q22015PromoId); if (promo != null) { var registDt = DateTime.Now; if (promo.StatusId == GlobalConfig.Visible && promo.StartDate < registDt && promo.EndDate > registDt) { ViewBag.IsPromoQ22015 = true; ViewBag.PreventAutoRenewalCheckboxFromUntick = true; productIds = q22015promo; // discounted 1month premium //get amount of 3 month premium var premium1mo = context.Products.FirstOrDefault(p => p.ProductId == 1); if (premium1mo != null) ViewBag.Premium1MonthPrice = premium1mo.ProductPrices.FirstOrDefault(p => String.Compare(p.CurrencyCode, country.CurrencyCode, true) == 0); //check purchasetry try { var user_purchases = context.PurchaseItems.Where(p => q22015promo.Contains(p.ProductId) && p.RecipientUserId == user.UserId); if (user_purchases != null) { var purchaseIds = user_purchases.Select(p => p.PurchaseId); var purchases = context.Purchases.Count(p => purchaseIds.Contains(p.PurchaseId) && p.Date > promo.StartDate && p.Date < promo.EndDate); if (purchases > 0) ViewBag.UserHasAvailedOfQ22015Promo = true; } } catch (Exception) { } } } } #endregion } #endregion } #endregion #region code for shwoing all the products else { var premiumProductGroupIds = MyUtility.StringToIntList(GlobalConfig.premiumProductGroupIds); var productGroup = context.ProductGroups.Where(p => premiumProductGroupIds.Contains(p.ProductGroupId)); if (productGroup != null) { foreach (var gr in productGroup) { var groupProductIds = gr.SubscriptionProducts.Select(p => p.ProductId); productIds = productIds.Union(groupProductIds); } } } #endregion ViewBag.IsAlaCarteProduct = IsAlaCarteProduct; //Check for Recurring Billing List<int> recurring_packages = null; if (User.Identity.IsAuthenticated) { var recurring = context.RecurringBillings.Where(r => r.UserId == user.UserId && r.StatusId == GlobalConfig.Visible); if (recurring != null) recurring_packages = recurring.Select(r => r.PackageId).ToList(); } var products = context.Products.Where(p => productIds.Contains(p.ProductId) && p is SubscriptionProduct); #region products not null if (products != null) { if (products.Count() > 0) { Product freeProduct = null; ProductPrice freeProductPrice = null; #region not required according to Albin bool IsXoomUser = false; if (User.Identity.IsAuthenticated) { //XOOM 2 Promo IsXoomUser = ContextHelper.IsXoomEligible(context, user); if (IsXoomUser) { var freeProductId = context.Products.FirstOrDefault(p => p.ProductId == GlobalConfig.Xoom2FreeProductId); if (freeProductId != null) if (freeProductId is SubscriptionProduct) { freeProduct = (SubscriptionProduct)freeProductId; try { freeProductPrice = freeProductId.ProductPrices.FirstOrDefault(p => String.Compare(p.CurrencyCode, country.CurrencyCode, true) == 0); ViewBag.IsAPRBoxDisabled = true; ViewBag.PageDescription = "Choose a package and provide your credit card or PayPal details to finish your registration and get your 1st month FREE!"; TempData["xoom"] = true; } catch (Exception) { } } } } #endregion productList = new List<SubscriptionProductA>(); foreach (SubscriptionProduct item in products) { if (item.IsAllowed(CountryCode) && item.IsForSale && item.StatusId == GlobalConfig.Visible) { #region pakage subscription if (item is PackageSubscriptionProduct) { var psp = (PackageSubscriptionProduct)item; var package = psp.Packages.FirstOrDefault(); if (package != null) { int counter = package.Package.GetAllOnlineShowIds(CountryCode).Count(); var sItem = new SubscriptionProductA() { package = (Package)package.Package, product = item, contentCount = counter, contentDescription = ContentDescriptionFlooring(counter > 1 ? counter - 1 : counter, true), ListOfDescription = ContextHelper.GetPackageFeatures(CountryCode, package), IsUserEnrolledToSameRecurringPackage = recurring_packages == null ? false : recurring_packages.Contains(package.PackageId) }; try { if (!String.IsNullOrEmpty(psp.ProductGroup.Description)) sItem.Blurb = psp.ProductGroup.Blurb; } catch (Exception) { } if (item.RegularProductId != null) { try { var regularProduct = context.Products.FirstOrDefault(p => p.ProductId == item.RegularProductId); if (regularProduct != null) if (regularProduct is SubscriptionProduct) { sItem.regularProduct = (SubscriptionProduct)regularProduct; try { sItem.regularProductPrice = regularProduct.ProductPrices.FirstOrDefault(p => String.Compare(p.CurrencyCode, country.CurrencyCode, true) == 0); } catch (Exception) { } } } catch (Exception) { } } #region xoom user not required else if (IsXoomUser) { if (freeProductPrice != null && freeProduct != null) { sItem.freeProduct = (SubscriptionProduct)freeProduct; sItem.freeProductPrice = freeProductPrice; } } #endregion try { sItem.productPrice = item.ProductPrices.FirstOrDefault(p => String.Compare(p.CurrencyCode, country.CurrencyCode, true) == 0); if (sItem.productPrice != null) productList.Add(sItem); } catch (Exception) { ViewBag.ProductPriceError = true; } } } #endregion #region show subscription else if (item is ShowSubscriptionProduct) { var ssp = (ShowSubscriptionProduct)item; var category = ssp.Categories.FirstOrDefault(); if (category != null) { var sItem = new SubscriptionProductA() { product = item, contentCount = 1, show = category.Show, ShowDescription = category.Show.Blurb }; try { if (!String.IsNullOrEmpty(ssp.ProductGroup.Description)) sItem.Blurb = ssp.ProductGroup.Description; } catch (Exception) { } try { sItem.productPrice = item.ProductPrices.FirstOrDefault(p => String.Compare(p.CurrencyCode, country.CurrencyCode, true) == 0); if (sItem.productPrice != null) productList.Add(sItem); } catch (Exception) { ViewBag.ProductPriceError = true; } } } #endregion } } } } #endregion else return RedirectToAction("Index", "Home"); #region //var productPackages = context.ProductPackages.Where(p => productIds.Contains(p.ProductId)); //if (productPackages != null) //{ // if (productPackages.Count() > 0) // { // productList = new List<SubscriptionProductA>(); // foreach (var item in productPackages) // { // if (item.Product.IsAllowed(CountryCode) && item.Product.IsForSale && item.Product.StatusId == GlobalConfig.Visible) // { // var package = item.Product.Packages.FirstOrDefault(); // if (package != null) // { // int counter = item.Package.GetAllOnlineShowIds(CountryCode).Count(); // var sItem = new SubscriptionProductA() // { // package = (Package)item.Package, // product = item.Product, // contentCount = counter, // contentDescription = ContentDescriptionFlooring(counter > 1 ? counter - 1 : counter, true), // ListOfDescription = ContextHelper.GetPackageFeatures(CountryCode, package) // }; // try // { // sItem.productPrice = item.Product.ProductPrices.FirstOrDefault(p => String.Compare(p.CurrencyCode, country.CurrencyCode, true) == 0); // productList.Add(sItem); // } // catch (Exception) { ViewBag.ProductPriceError = true; } // } // } // } // } //} #endregion #region product list not null if (productList != null) { if (productList.Count() > 0) { #region productList.Count() > 0 //Credit card ViewBag.HasCreditCardEnrolled = false; ViewBag.CreditCardAvailability = true; try { ArrayList list = new ArrayList(); for (int i = 0; i < 12; i++) { SelectListItem item = new SelectListItem() { Value = (i + 1).ToString(), Text = DateTimeFormatInfo.CurrentInfo.GetMonthName(i + 1) }; list.Add(item); } ViewBag.Months = list; list = new ArrayList(); int currentYear = DateTime.Now.Year; for (int i = currentYear; i <= currentYear + 20; i++) { SelectListItem item = new SelectListItem() { Value = i.ToString(), Text = i.ToString() }; list.Add(item); } ViewBag.Years = list; if (User.Identity.IsAuthenticated) { //Get Credit Card List var ccTypes = user.Country.GetGomsCreditCardTypes(); if (user.Country.GomsSubsidiaryId != GlobalConfig.MiddleEastGomsSubsidiaryId) ccTypes = user.Country.GetGomsCreditCardTypes(); else { var listOfMiddleEastAllowedCountries = GlobalConfig.MECountriesAllowedForCreditCard.Split(','); if (listOfMiddleEastAllowedCountries.Contains(user.Country.Code)) ccTypes = user.Country.GetGomsCreditCardTypes(); else ccTypes = null; } if (ccTypes == null) ViewBag.CreditCardAvailability = false; else { List<TFCTV.Helpers.CreditCard> clist = new List<TFCTV.Helpers.CreditCard>(); foreach (var item in ccTypes) clist.Add(new TFCTV.Helpers.CreditCard() { value = ((int)item).ToString(), text = item.ToString().Replace('_', ' ') }); ViewBag.CreditCardList = clist; } if (GlobalConfig.IsRecurringBillingEnabled) { var UserCreditCard = user.CreditCards.FirstOrDefault(c => c.StatusId == GlobalConfig.Visible && c.OfferingId == offering.OfferingId); if (UserCreditCard != null) { ViewBag.HasCreditCardEnrolled = true; ViewBag.UserCreditCard = UserCreditCard; } } } else { var cCountry = context.Countries.FirstOrDefault(c => String.Compare(c.Code, location.countryCode, true) == 0); if (cCountry != null) { var ccTypes = cCountry.GetGomsCreditCardTypes(); if (cCountry.GomsSubsidiaryId != GlobalConfig.MiddleEastGomsSubsidiaryId) ccTypes = cCountry.GetGomsCreditCardTypes(); else { var listOfMiddleEastAllowedCountries = GlobalConfig.MECountriesAllowedForCreditCard.Split(','); if (listOfMiddleEastAllowedCountries.Contains(cCountry.Code)) ccTypes = cCountry.GetGomsCreditCardTypes(); else ccTypes = null; } if (ccTypes == null) ViewBag.CreditCardAvailability = false; else { List<TFCTV.Helpers.CreditCard> clist = new List<TFCTV.Helpers.CreditCard>(); foreach (var item in ccTypes) clist.Add(new TFCTV.Helpers.CreditCard() { value = ((int)item).ToString(), text = item.ToString().Replace('_', ' ') }); ViewBag.CreditCardList = clist; } } } } catch (Exception) { } if (User.Identity.IsAuthenticated) { //E-Wallet ViewBag.InsufficientWalletBalance = false; try { var userWallet = user.UserWallets.FirstOrDefault(u => String.Compare(u.Currency, user.Country.CurrencyCode, true) == 0 && u.IsActive == true); if (userWallet != null) { var UserCurrencyCode = user.Country.CurrencyCode; var productPrice = productList.First().product.ProductPrices.FirstOrDefault(p => String.Compare(p.CurrencyCode, UserCurrencyCode, true) == 0); if (productPrice == null) productPrice = productList.First().product.ProductPrices.FirstOrDefault(p => String.Compare(p.CurrencyCode, GlobalConfig.DefaultCurrency, true) == 0); ViewBag.ProductPrice = productPrice; if (productPrice.Amount > userWallet.Balance) ViewBag.InsufficientWalletBalance = true; } } catch (Exception) { } //check if user is first time subscriber ViewBag.IsFirstTimeSubscriber = user.IsFirstTimeSubscriber(offering); } #endregion } } if (productList != null) if (productList.Count() > 0) { if (String.Compare(id, GlobalConfig.PacMaySubscribeCategoryId.ToString(), true) == 0 && !User.Identity.IsAuthenticated) return View("DetailsPacMay2", productList); else { if (ProductOption != null) ViewBag.ProductOption = (int)ProductOption; return View("Details5", productList); } } return RedirectToAction("Details", new { id = String.Empty }); #endregion #endregion } catch (Exception e) { MyUtility.LogException(e); } return RedirectToAction("Index", "Home"); } #endregion #region else for the above if else { List<SubscriptionProductA> productList = null; try { var countryCode = MyUtility.GetCurrentCountryCodeOrDefault(); var context = new IPTV2Entities(); var country = context.Countries.FirstOrDefault(c => String.Compare(c.Code, countryCode, true) == 0); var offering = context.Offerings.Find(GlobalConfig.offeringId); var service = offering.Services.FirstOrDefault(o => o.PackageId == GlobalConfig.serviceId); var listOfPackagesInProductGroup = MyUtility.StringToIntList(GlobalConfig.PackagesInProductGroup); if (!String.IsNullOrEmpty(id)) { int pid = 0; try { pid = Int32.Parse(id); } catch (Exception) { } ViewBag.id = pid; using (profiler.Step("Get Subscription (w/ parameter)")) { var show = (Show)context.CategoryClasses.Find(pid); /******* CHECK IF SHOW IS VIEWABLE VIA USER'S COUNTRY CODE & COUNTRY CODE BASED ON IP ADDRESS *****/ if (!ContextHelper.IsCategoryViewableInUserCountry(show, countryCode)) return RedirectToAction("Index", "Home"); string CountryCodeBasedOnIpAddress = MyUtility.GetCountryCodeViaIpAddressWithoutProxy(); if (!ContextHelper.IsCategoryViewableInUserCountry(show, CountryCodeBasedOnIpAddress)) return RedirectToAction("Index", "Home"); ViewBag.ShowName = show.Description; SortedSet<Int32> productIds = new SortedSet<int>(); var packageProductIds = show.GetPackageProductIds(offering, countryCode, RightsType.Online); if (packageProductIds != null) productIds.UnionWith(packageProductIds); var showProductIds = show.GetShowProductIds(offering, countryCode, RightsType.Online); if (showProductIds != null) productIds.UnionWith(showProductIds); ViewBag.PackageProductIds = packageProductIds; ViewBag.ShowProductIds = showProductIds; var products = context.Products.Where(p => productIds.Contains(p.ProductId)); List<PackageContentSummary> contentSummary = new List<PackageContentSummary>(); if (products != null) { productList = new List<SubscriptionProductA>(); foreach (var product in products) { if (product.IsForSale && product.StatusId == GlobalConfig.Visible) { if (product is SubscriptionProduct) { if (product is PackageSubscriptionProduct) { var pkgSubscriptionProduct = (PackageSubscriptionProduct)product; var package = pkgSubscriptionProduct.Packages.FirstOrDefault(); var counter = 0; var item = new SubscriptionProductA() { product = (SubscriptionProduct)product, productGroup = pkgSubscriptionProduct.ProductGroup, isPackage = true }; //SET DEFAULT PRODUCT ID VIA PARAM if (PackageOption != null) { if (listOfPackagesInProductGroup.Contains((int)PackageOption)) if (pkgSubscriptionProduct.ProductGroupId == PackageOption) if (ProductOption != null) item.productGroup.DefaultProductId = ProductOption; } if (package != null) { // make sure that this doesnt repeat. save data in list if (!contentSummary.Select(s => s.PackageId).Contains(package.PackageId)) { foreach (var cat in package.Package.Categories) { if (cat.Category is Category) counter += service.GetAllOnlineShowIds(countryCode, (Category)cat.Category).Count(); } contentSummary.Add(new PackageContentSummary() { PackageId = package.PackageId, ContentCount = counter }); } else counter = contentSummary.FirstOrDefault(s => s.PackageId == package.PackageId).ContentCount; item.contentCount = counter; //for description of content item.contentDescription = ContentDescriptionFlooring(counter > 1 ? counter - 1 : counter, true); item.package = (Package)package.Package; item.ListOfDescription = ContextHelper.GetPackageFeatures(countryCode, package); if (item.productGroup.ProductSubscriptionTypeId != null) item.ShowDescription = show.Blurb; } try { item.productPrice = pkgSubscriptionProduct.ProductPrices.FirstOrDefault(p => p.CurrencyCode == country.CurrencyCode); productList.Add(item); } catch (Exception) { ViewBag.ProductPriceError = true; } } else if (product is ShowSubscriptionProduct) { var shwSubscriptionProduct = (ShowSubscriptionProduct)product; var category = shwSubscriptionProduct.Categories.FirstOrDefault(); var item = new SubscriptionProductA() { product = (SubscriptionProduct)product, productGroup = shwSubscriptionProduct.ProductGroup, contentCount = 1 }; if (category != null) { item.show = category.Show; item.ShowDescription = category.Show.Blurb; } try { item.productPrice = shwSubscriptionProduct.ProductPrices.FirstOrDefault(p => p.CurrencyCode == country.CurrencyCode); productList.Add(item); } catch (Exception) { ViewBag.ProductPriceError = true; } } } } } } } } else { using (profiler.Step("Get Subscription (no parameter)")) { var groups = context.ProductGroups.Where(p => listOfPackagesInProductGroup.Contains(p.ProductGroupId)); if (groups != null) { List<PackageContentSummary> contentSummary = new List<PackageContentSummary>(); productList = new List<SubscriptionProductA>(); foreach (var grp in groups) { foreach (var product in grp.SubscriptionProducts) { if (product.IsAllowed(countryCode)) { if (product.IsForSale && product.StatusId == GlobalConfig.Visible) { if (product is PackageSubscriptionProduct) { var pkgSubscriptionProduct = (PackageSubscriptionProduct)product; var package = pkgSubscriptionProduct.Packages.FirstOrDefault(); var counter = 0; var item = new SubscriptionProductA() { product = product, productGroup = pkgSubscriptionProduct.ProductGroup, isPackage = true }; //SET DEFAULT PRODUCT ID VIA PARAM if (PackageOption != null) { if (listOfPackagesInProductGroup.Contains((int)PackageOption)) if (pkgSubscriptionProduct.ProductGroupId == PackageOption) if (ProductOption != null) item.productGroup.DefaultProductId = ProductOption; } if (package != null) { // make sure that this doesnt repeat. save data in list if (!contentSummary.Select(s => s.PackageId).Contains(package.PackageId)) { foreach (var cat in package.Package.Categories) { if (cat.Category is Category) counter += service.GetAllOnlineShowIds(countryCode, (Category)cat.Category).Count(); } contentSummary.Add(new PackageContentSummary() { PackageId = package.PackageId, ContentCount = counter }); } else counter = contentSummary.FirstOrDefault(s => s.PackageId == package.PackageId).ContentCount; item.contentCount = counter; item.contentDescription = ContentDescriptionFlooring(counter, true); item.package = (Package)package.Package; item.ListOfDescription = ContextHelper.GetPackageFeatures(countryCode, package); } try { item.productPrice = pkgSubscriptionProduct.ProductPrices.FirstOrDefault(p => p.CurrencyCode == country.CurrencyCode); productList.Add(item); } catch (Exception) { ViewBag.ProductPriceError = true; } } } } } } } } } // SET DEFAULT PACKAGE. Position Swap! if (productList != null) { if (productList.Count() > 0) { if (PackageOption != null) { int index = 0; if (listOfPackagesInProductGroup.Contains((int)PackageOption)) index = productList.FindIndex(x => x.productGroup.ProductGroupId == PackageOption); else index = productList.FindIndex(x => !listOfPackagesInProductGroup.Contains(x.productGroup.ProductGroupId)); if (index > 0) { var item = productList[index]; productList[index] = productList[0]; productList[0] = item; } } } } //Only return if productList is not empty and count > 0 if (productList != null) if (productList.Count() > 0) return View("Details5", productList); } catch (Exception e) { MyUtility.LogException(e); } return RedirectToAction("Index", "Home"); } #endregion }
public List<Chain> DataTableGetChainForCondition(SortedSet<IL> setIL, int wh) { var source = DataTableGet(Table.TableRowSource.Name); if (source == null) return null; if (source.Rows.Count == 0) return null; var chainGroup = new List<Chain>(); foreach (DataRow row in source.Rows) { var il = new IL { Item = row.GetItem(), Loc = row.GetLoc() }; if (!setIL.Contains(il)) continue; var chain = LogisticChainGet(row.GetItem(), row.GetLoc(), wh); chainGroup.Add(chain); } Chain.Group(chainGroup); return chainGroup; }
public bool DataTableRowSourceUpdateCustom(List<FieldValue> setValues, SortedSet<IL> setIL, ref SortedSet<IL> lockedIL) { var sourceRow = DataTableGet(Table.TableRowSource.Name); var sourceSec = DataTableGet(Table.TableSecSource.Name); if (sourceRow == null || sourceSec == null) return false; var rows = new List<DataRow>(); foreach (var il in setIL) { var rowRow = sourceRow.Rows.Find(new[] { (object)il.Item, (object)il.Loc }); var rowSec = sourceSec.Rows.Find(new[] { (object)il.Item, (object)il.Loc }); if (rowRow.GetAction() == Actions.Delete) continue; if (!CheckPermissions3(rowRow, setValues)) { if (!lockedIL.Contains(il)) lockedIL.Add(il); continue; } foreach (var value in setValues) { if (value.Field == "ACTION" && (int)value.Value == (int)Actions.Leave) { rowRow["ACTION"] = rowRow.GetMeasureStatus() == MeasureStatuses.NotInAssortment ? (int)Actions.Leave : (int)Actions.Modify; rowSec["ACTION"] = rowRow["ACTION"]; } else { if (value.Field == "DIM_ITEMLOC_SOURCEMETHOD_NEW" && (char)value.Value == (char)SourceMethods.S && rowRow.GetAction() == Actions.Close) { rowRow["ACTION"] = rowRow.GetMeasureStatus() == MeasureStatuses.NotInAssortment ? (int)Actions.Leave : (int)Actions.Modify; rowSec["ACTION"] = rowRow["ACTION"]; } rowRow[value.Field] = value.Value ?? DBNull.Value; rowSec[value.Field] = rowRow[value.Field]; } } rows.Add(rowRow); rowSec.AcceptChanges(); } try { if (rows.Count > 0) { ((OracleDataAdapter)_adapters[Table.TableRowSource.Name]).Update(rows.ToArray()); DocChanged(this, null); } } catch (Exception ex) { Error = ex.Message; return false; } //DataTableSecSourceUpdateCustomWithoutDb(setValues, setIL); return true; }
public bool DataTableSecSourceUpdateStatus(FormActions actionType, SortedSet<IL> setIL, ref SortedSet<IL> lockedIL) { var source = DataTableGet(Table.TableSecSource.Name); if (source == null) return false; var rows = new List<DataRow>(); var stateRows = new StateRows(); foreach (var il in setIL) { var row = source.Rows.Find(new[] { (object)il.Item, (object)il.Loc }); //if (row.GetLocType() == LocTypes.W && row.GetItemType() != ItemTypes.ExpendMaterial) continue; if (!CheckPermissions2(row, actionType)) { if (!lockedIL.Contains(il)) lockedIL.Add(il); continue; } var action = row.GetAction(); var measureStatus = row.GetMeasureStatus(); var measureStatusNew = row.GetMeasureStatusNew(); object actionWrite = null; object measureStatusNewWrite = null; switch (actionType) { case FormActions.Add: { measureStatusNewWrite = MeasureStatuses.InAssortment; if (measureStatus == MeasureStatuses.NotInAssortment) { if (measureStatusNew == MeasureStatuses.NotInAssortment && action == Actions.Delete) actionWrite = Actions.NoAction; else actionWrite = Actions.Leave; } else { if (measureStatusNew == MeasureStatuses.NotInAssortment) actionWrite = action == Actions.NoAction ? Actions.Leave : Actions.NoAction; else actionWrite = action; } break; } case FormActions.Delete: { measureStatusNewWrite = MeasureStatuses.NotInAssortment; if (row["DIM_ITEMLOC_SUPPLIER"] != DBNull.Value) row["DIM_ITEMLOC_SUPPLIER_NEW"] = row["DIM_ITEMLOC_SUPPLIER"]; if (row["DIM_ITEMLOC_SUPPLIER_DESC_NEW"] != DBNull.Value) row["DIM_ITEMLOC_SUPPLIER_DESC_NEW"] = row["DIM_ITEMLOC_SUPPLIER_DESC"]; if (row.GetOrderPlaceNew() != OrderPlaces.None) row["DIM_ITEMLOC_ORDERPLACE_NEW"] = row["DIM_ITEMLOC_ORDERPLACE"]; else row["DIM_ITEMLOC_ORDERPLACE_NEW"] = 3; if (row.GetSourceMethodNew() != SourceMethods.None && row.GetSourceMethodNew() == SourceMethods.T) row["DIM_ITEMLOC_SOURCEWH_NEW"] = DBNull.Value; row["DIM_ITEMLOC_SOURCEMETHOD_NEW"] = (char)SourceMethods.S; if (row["DIM_ITEMLOC_SOURCEWH"] != DBNull.Value) row["DIM_ITEMLOC_SOURCEWH_NEW"] = row["DIM_ITEMLOC_SOURCEWH"]; if (measureStatus == MeasureStatuses.InAssortment) actionWrite = Actions.Delete; else { if (measureStatusNew == MeasureStatuses.InAssortment) actionWrite = action == Actions.NoAction ? Actions.Delete : Actions.NoAction; else actionWrite = action; } break; } case FormActions.Modify: { measureStatusNewWrite = measureStatusNew; actionWrite = (action == Actions.NoAction && measureStatusNew == MeasureStatuses.InAssortment) ? Actions.Modify : action; // Cleanup SourceMethodNew if permission type is 'W' if (UserStoreList.ContainsKey(Convert.ToInt32(il.Loc))) if (UserStoreList[Convert.ToInt32(il.Loc)] == LocPermissionTypes.WarehouseTransit) if (row.GetSourceMethod() == SourceMethods.S && row.GetSourceMethodNew() == SourceMethods.S) row["DIM_ITEMLOC_SOURCEMETHOD_NEW"] = DBNull.Value; break; } case FormActions.ModifyCancel: { measureStatusNewWrite = measureStatusNew; actionWrite = action == Actions.Modify ? Actions.NoAction : action; break; } case FormActions.Restore: { measureStatusNewWrite = measureStatus; actionWrite = Actions.NoAction; row["DIM_ITEMLOC_SUPPLIER_NEW"] = row["DIM_ITEMLOC_SUPPLIER"]; row["DIM_ITEMLOC_SUPPLIER_DESC_NEW"] = row["DIM_ITEMLOC_SUPPLIER_DESC"]; row["DIM_ITEMLOC_ORDERPLACE_NEW"] = row["DIM_ITEMLOC_ORDERPLACE"]; row["DIM_ITEMLOC_SOURCEMETHOD_NEW"] = row["DIM_ITEMLOC_SOURCEMETHOD"]; row["DIM_ITEMLOC_SOURCEWH_NEW"] = row["DIM_ITEMLOC_SOURCEWH"]; break; } } // Save row state stateRows.Rows.Add(new StateRow { Item = row.GetItem(), Loc = row.GetLoc(), FieldsValuesPrevious = new List<FieldValue> { new FieldValue { Field = "ACTION", Value = (int)action }, new FieldValue { Field = "MEASURE_STATUS_NEW", Value = (int)measureStatusNew } }, FieldsValuesNext = new List<FieldValue> { new FieldValue { Field = "ACTION", Value = (int)actionWrite }, new FieldValue { Field = "MEASURE_STATUS_NEW", Value = (int)measureStatusNewWrite } } }); row["ACTION"] = (int)actionWrite; row["MEASURE_STATUS_NEW"] = (int)measureStatusNewWrite; rows.Add(row); } Steps.CreateNewState(stateRows); try { if (rows.Count > 0) { ((OracleDataAdapter)_adapters[Table.TableSecSource.Name]).Update(rows.ToArray()); DocChanged(this, new EventArgs()); } } catch (Exception ex) { Error = ex.Message; return false; } return true; }
private Outcome CheckSplit(SortedSet<int> split, ref bool popLater, int timeLimit, int timeLimitPerAssertion, ref int queries) { var tla = timeLimitPerAssertion * split.Count; if (popLater) { SendThisVC("(pop 1)"); } SendThisVC("(push 1)"); SendThisVC(string.Format("(set-option :{0} {1})", Z3.SetTimeoutOption(), (0 < tla && tla < timeLimit) ? tla : timeLimit)); popLater = true; SendThisVC(string.Format("; checking split VC with {0} unverified assertions", split.Count)); var expr = VCExpressionGenerator.True; foreach (var i in ctx.TimeoutDiagnosticIDToAssertion.Keys) { var lit = VCExprGen.Function(VCExpressionGenerator.TimeoutDiagnosticsOp, VCExprGen.Integer(Microsoft.Basetypes.BigNum.FromInt(i))); if (split.Contains(i)) { lit = VCExprGen.Not(lit); } expr = VCExprGen.AndSimp(expr, lit); } SendThisVC("(assert " + VCExpr2String(expr, 1) + ")"); if (options.Solver == SolverKind.Z3) { SendThisVC("(apply (then (using-params propagate-values :max_rounds 1) simplify) :print false)"); } FlushLogFile(); SendCheckSat(); queries++; return GetResponse(); }
public void Contains () { var set = new SortedSet<int> { 2, 3, 4, 5 }; Assert.IsTrue (set.Contains (4)); Assert.IsFalse (set.Contains (7)); }
public void TestRankingOK() { int count = 10; var p = new Person(count, new Random()); var seen = new SortedSet<int>(); foreach (var candidate in Enumerable.Range(0, 10)) { var r = p.Ranking(candidate); Assert.IsFalse(seen.Contains(r), "Duplicate ranking"); seen.Add(r); Console.WriteLine("Candiate {0} has rank {1}.", candidate, r); } Assert.AreEqual(count, seen.Count, "Size of the count"); }
public void ViewRemove () { var set = new SortedSet<int> { 1, 3, 5, 7, 9 }; var view = set.GetViewBetween (3, 7); Assert.IsTrue (view.Remove (3)); Assert.IsFalse (view.Contains (3)); Assert.IsFalse (set.Contains (3)); Assert.IsFalse (view.Remove (9)); Assert.IsTrue (set.Contains (9)); }
/// <summary> /// Make sure this guy is contiguous. /// </summary> /// <param name="rankings"></param> private static void CheckContiguous(int[] rankings, int properSize) { Assert.AreEqual(properSize, rankings.Length, "Array lenght incorrect"); var s = new SortedSet<int>(rankings); Assert.AreEqual(properSize, s.Count, "There were some non-unique numbers in there!"); foreach (var i in Enumerable.Range(0, properSize)) { Assert.IsTrue(s.Contains(i), string.Format("Missing element {0}.", i)); } }
private static void TestFullRankingWithOneGoneParameterized(Person p) { var fr = p.FullRanking(new int[] { 1 }).ToArray(); Assert.AreEqual(2, fr.Length, "Incorrect number came back"); CheckContiguous(fr.Select(c => c.ranking).ToArray(), 2); var s = new SortedSet<int>(fr.Select(c => c.candidate)); Assert.IsFalse(s.Contains(1), "candidate 1 should not be in there"); var fullOrdering = (from c in p.FullRanking() orderby c.ranking ascending select c).ToArray(); var partialOrdering = (from c in fr orderby c.ranking ascending select c).ToArray(); int i_p = 0; for (int i_f = 0; i_f < fullOrdering.Length; i_f++) { if (fullOrdering[i_f].candidate != 1) { if (fullOrdering[i_f].candidate == partialOrdering[i_p].candidate) { i_p++; } } } Assert.AreEqual(partialOrdering.Length, i_p, "Partial list not ordered correctly"); }
private List<PathCoordinate> GeneratePath(PathCoordinate start, PathCoordinate end, Size size, double maxDistance) { SortedSet<PathCoordinate> sortedPath = new SortedSet<PathCoordinate>(new PathCoordinateDistanceToTargetComparer()); List<PathCoordinate> path = new List<PathCoordinate>(); _firstCoordinate = start; _firstCoordinate.DistanceToTarget = _firstCoordinate.DistanceTo(end); PathCoordinate currentCoordinate = start; int loopsLeft = 1000; while (currentCoordinate != null && currentCoordinate != end && loopsLeft > 0) { currentCoordinate.Checked = true; loopsLeft--; PathCoordinate[] pathOptions = GetPathOptions(currentCoordinate, end, size, maxDistance); foreach (var option in pathOptions) { double distance = currentCoordinate.DistanceFromStart + currentCoordinate.DistanceTo(option); bool existsInPath = sortedPath.Contains(option); if (!existsInPath || distance < option.DistanceFromStart) { option.PreviousCoordinate = currentCoordinate; if (existsInPath) { sortedPath.Remove(option); option.SetDistanceFromStartAndTarget(distance, option.DistanceTo(end)); sortedPath.Add(option); } else { option.SetDistanceFromStartAndTarget(distance, option.DistanceTo(end)); sortedPath.Add(option); } } } sortedPath.Remove(currentCoordinate); if (sortedPath.Count > 0) currentCoordinate = sortedPath.Min; else break; } if (currentCoordinate == null || currentCoordinate == _firstCoordinate) return null; // currentCoordinate is destination so walk up previous coordinates and add to list, then reverse List<PathCoordinate> result = new List<PathCoordinate> {currentCoordinate}; while (currentCoordinate.PreviousCoordinate != null) { result.Add(currentCoordinate.PreviousCoordinate); currentCoordinate = currentCoordinate.PreviousCoordinate; } result.Reverse(); return result; }
public JsonResult MyVideos() { if (!GlobalConfig.IsSynapseEnabled) return Json(null, JsonRequestBehavior.AllowGet); DateTime registDt = DateTime.Now; List<EntitlementDisplay> display = new List<EntitlementDisplay>(); if (User.Identity.IsAuthenticated) { System.Guid userId = new System.Guid(User.Identity.Name); var context = new IPTV2Entities(); User user = context.Users.FirstOrDefault(u => u.UserId == userId); if (user != null) { var entitlements = context.Entitlements.Where(t => t.UserId == user.UserId && t.OfferingId == GlobalConfig.offeringId && t.EndDate > registDt).OrderByDescending(t => t.EndDate).ToList(); var offering = context.Offerings.Find(GlobalConfig.offeringId); var service = offering.Services.FirstOrDefault(s => s.PackageId == GlobalConfig.serviceId && s.StatusId == GlobalConfig.Visible); SortedSet<int> mobileShowIds = new SortedSet<int>(); try { mobileShowIds = service.GetAllMobileShowIds(user.CountryCode); } catch (Exception) { } foreach (Entitlement entitlement in entitlements) { EntitlementDisplay disp = new EntitlementDisplay(); disp.EntitlementId = entitlement.EntitlementId; disp.ExpiryDate = entitlement.EndDate; disp.ExpiryDateStr = entitlement.EndDate.ToString("yyyy-MM-ddThh:mm:ss"); //disp.ExpiryDateStr = entitlement.EndDate.ToString("yyyy-MM-dd"); if (entitlement is PackageEntitlement) { var pkg = (PackageEntitlement)entitlement; disp.PackageId = pkg.PackageId; disp.PackageName = pkg.Package.Description; disp.Content = disp.PackageName; } else if (entitlement is ShowEntitlement) { var show = (ShowEntitlement)entitlement; if (mobileShowIds.Contains(show.CategoryId)) { if (!(show.Show is LiveEvent)) { disp.CategoryId = show.CategoryId; disp.CategoryName = show.Show.Description; disp.Content = disp.CategoryName; } } } else if (entitlement is EpisodeEntitlement) { var episode = (EpisodeEntitlement)entitlement; disp.EpisodeId = episode.EpisodeId; disp.EpisodeName = episode.Episode.Description + ", " + episode.Episode.DateAired.Value.ToString("MMM d, yyyy"); disp.Content = disp.EpisodeName; } display.Add(disp); } } } return this.Json(display, JsonRequestBehavior.AllowGet); }
private int getNextValidVertex(SortedSet<int> set, Group group, int oldVertex, int p, int n) { Debug.Assert(group.SubGroups.Count != 0); int vertex = oldVertex + 1; while (set.Contains(vertex) && vertex < n) { ++vertex; } if (vertex < n - p + group.SubGroups.Count + 1) { return vertex; } return -1; }