Exemple #1
0
        public static ICache CreateDefault()
        {
            string cacheProvider = ConfigurationManager.AppSettings["CacheProvider"] ?? string.Empty;
            ICache cache = null;

            if (!DictCacheProviders.TryGetValue(cacheProvider, out cache))
            {
                lock (SyncRoot)
                {
                    if (!DictCacheProviders.TryGetValue(cacheProvider, out cache))
                    {
                        if (!string.IsNullOrWhiteSpace(cacheProvider))
                        {
                            cache = (ICache)Activator.CreateInstance(Type.GetType(cacheProvider));
                        }
                        else
                            cache = new WebCache();
                        DictCacheProviders.Add(cacheProvider, cache);
                    }
                }
            }

            return cache;
        }
        private void AddContentItem(ThemeConfig theme, FeedSectionData content)
        {
            switch (content.content_type)
            {
            case "headline":
                /*
                 * {
                 *      // use the Golden Ratio to calculate an attractive size relative to the banner
                 *      var image = new ImageBuffer(1520, (int)(170 / 1.618));
                 *      var imageWidget = new ResponsiveImageWidget(image)
                 *      {
                 *              Margin = new BorderDouble(5),
                 *              Cursor = Cursors.Hand
                 *      };
                 *
                 *      var graphics2D = image.NewGraphics2D();
                 *      image.SetRecieveBlender(new BlenderPreMultBGRA());
                 *      graphics2D.Clear(theme.AccentMimimalOverlay);
                 *
                 *      // use the Golden Ratio to calculate an attractive size for the text relative to the text banner
                 *      var pixelsPerPoint = 96.0 / 72.0;
                 *      var goalPointSize = image.Height / pixelsPerPoint / 1.618;
                 *
                 *      var printer = new TypeFacePrinter(content.text, goalPointSize);
                 *
                 *      graphics2D.DrawString(content.text, image.Width/2, image.Height/2 + printer.TypeFaceStyle.EmSizeInPixels / 2, goalPointSize,
                 *              Justification.Center, Baseline.BoundsTop,
                 *              theme.TextColor);
                 *
                 *      if (content.link != null)
                 *      {
                 *              imageWidget.Cursor = Cursors.Hand;
                 *              imageWidget.Click += (s, e) =>
                 *              {
                 *                      if (e.Button == MouseButtons.Left)
                 *                      {
                 *                              ApplicationController.LaunchBrowser(content.link);
                 *                      }
                 *              };
                 *      }
                 *
                 *      container.Add(imageWidget);
                 * }
                 */
                break;

            case "banner_rotate":
                // TODO: make this make a carousel rather than add the first item and rotate between all the items
                var rand = new Random();
                AddContentItem(theme, content.banner_list[rand.Next(content.banner_list.Count)]);
                break;

            case "banner_image":
            {
                // Our banners seem to end with something like "=w1520-h170"
                // if present use that to get the right width and height
                int expectedWidth = 1520;
                GCodeFile.GetFirstNumberAfter("=w", content.image_url, ref expectedWidth);
                int expectedHeight = 170;
                GCodeFile.GetFirstNumberAfter("-h", content.image_url, ref expectedHeight);
                if ((content.theme_filter == "dark" && theme.IsDarkTheme) ||
                    (content.theme_filter == "light" && !theme.IsDarkTheme) ||
                    (content.theme_filter == "all"))
                {
                    var image       = new ImageBuffer(expectedWidth, expectedHeight);
                    var imageWidget = new ResponsiveImageWidget(image)
                    {
                        Margin = new BorderDouble(5),
                        Cursor = Cursors.Hand
                    };

                    if (content.link != null)
                    {
                        imageWidget.Cursor = Cursors.Hand;
                        imageWidget.Click += (s, e) =>
                        {
                            if (e.Button == MouseButtons.Left)
                            {
                                ApplicationController.LaunchBrowser(content.link);
                            }
                        };
                    }

                    AfterDraw += (s, e) =>
                    {
                        if (!loaded)
                        {
                            loaded = true;
                            WebCache.RetrieveImageAsync(image, content.image_url, false);
                        }
                    };
                    topBanner.AddChild(imageWidget);
                }
            }
            break;

            case "article_group":
            {
                // add the article group button to the button group
                // add a content section connected to the button
                var sectionButton = new TextButton(content.group_title, theme);
                sectionSelectButtons.AddChild(sectionButton);
                var articleSection = new ArticleSection(content, theme)
                {
                    Visible = false,
                    Name    = content.group_title
                };
                contentSection.AddChild(articleSection);
                sectionButton.Click += (s, e) =>
                {
                    foreach (var contentWidget in contentSection.Children)
                    {
                        contentWidget.Visible = contentWidget == articleSection;
                    }
                };
            }
            break;

            case "product_group":
            {
                var sectionButton = new TextButton(content.group_title, theme);
                sectionSelectButtons.AddChild(sectionButton);
                var exploreSection = new ProductSection(content, theme)
                {
                    Name = content.group_title
                };
                contentSection.AddChild(exploreSection);
                sectionButton.Click += (s, e) =>
                {
                    foreach (var contentWidget in contentSection.Children)
                    {
                        contentWidget.Visible = contentWidget == exploreSection;
                    }
                };
            }
            break;
            }
        }
 public static void Remove(string key)
 {
     WebCache.Remove(key);
 }
 public static void RemoveCache(CacheHelperKeys cacheKey = CacheHelperKeys.constCategoryList)
 {
     WebCache.Remove(cacheKey.ToString());
 }
 public static bool Set(string key, object value, DateTime expiry)
 {
     WebCache.Set(key, value, expiry);
     return(Provider.Set(key, value, expiry));
 }
 public static bool Delete(string key)
 {
     WebCache.Delete(key);
     return(Provider.Delete(key));
 }
Exemple #7
0
 public TfsUrlValidator(WebCache cache)
 {
     this.cache = cache;
 }
        private void AddContentItem(FeedSectionData content)
        {
            switch (content.content_type)
            {
            case "headline":
            {
                break;

                // use the Golden Ratio to calculate an attractive size relative to the banner
                var image       = new ImageBuffer(1520, (int)(170 / 1.618));
                var imageWidget = new ResponsiveImageWidget(image)
                {
                    Margin = new BorderDouble(5),
                    Cursor = Cursors.Hand
                };

                var graphics2D = image.NewGraphics2D();
                image.SetRecieveBlender(new BlenderPreMultBGRA());
                graphics2D.Clear(theme.AccentMimimalOverlay);

                // use the Golden Ratio to calculate an attractive size for the text relative to the text banner
                var pixelsPerPoint = 96.0 / 72.0;
                var goalPointSize  = image.Height / pixelsPerPoint / 1.618;

                var printer = new TypeFacePrinter(content.text, goalPointSize);

                graphics2D.DrawString(content.text, image.Width / 2, image.Height / 2 + printer.TypeFaceStyle.EmSizeInPixels / 2, goalPointSize,
                                      Justification.Center, Baseline.BoundsTop,
                                      theme.TextColor);

                if (content.link != null)
                {
                    imageWidget.Cursor = Cursors.Hand;
                    imageWidget.Click += (s, e) =>
                    {
                        if (e.Button == MouseButtons.Left)
                        {
                            ApplicationController.Instance.LaunchBrowser(content.link);
                        }
                    };
                }

                this.AddChild(imageWidget);
            }
            break;

            case "banner_rotate":
                // TODO: make this make a carousel rather than add the first item and rotate between all the items
                var rand = new Random();
                AddContentItem(content.banner_list[rand.Next(content.banner_list.Count)]);
                break;

            case "banner_image":
            {
                // Our banners seem to end with something like "=w1520-h170"
                // if present use that to get the right width and height
                int expectedWidth = 1520;
                GCodeFile.GetFirstNumberAfter("=w", content.image_url, ref expectedWidth);
                int expectedHeight = 170;
                GCodeFile.GetFirstNumberAfter("-h", content.image_url, ref expectedHeight);
                if ((content.theme_filter == "dark" && theme.IsDarkTheme) ||
                    (content.theme_filter == "light" && !theme.IsDarkTheme) ||
                    (content.theme_filter == "all"))
                {
                    var image       = new ImageBuffer(expectedWidth, expectedHeight);
                    var imageWidget = new ResponsiveImageWidget(image)
                    {
                        Margin = new BorderDouble(5),
                        Cursor = Cursors.Hand
                    };

                    if (content.link != null)
                    {
                        imageWidget.Cursor = Cursors.Hand;
                        imageWidget.Click += (s, e) =>
                        {
                            if (e.Button == MouseButtons.Left)
                            {
                                ApplicationController.Instance.LaunchBrowser(content.link);
                            }
                        };
                    }

                    imageWidget.Load += (s, e) => WebCache.RetrieveImageAsync(image, content.image_url, false, new BlenderPreMultBGRA());
                    this.AddChild(imageWidget);
                }
            }
            break;

            case "article_group":
            case "product_group":
                if (currentContentContainer == null)
                {
                    currentContentContainer = new FlowLeftRightWithWrapping();
                    this.AddChild(currentContentContainer);
                }
                currentContentContainer.AddChild(new ExploreSection(content, theme));
                break;
            }
        }
Exemple #9
0
        /// <summary>
        /// Gets the specified download item.
        /// </summary>
        /// <param name="downloadItem">The download item.</param>
        public void Get(DownloadItem downloadItem)
        {
            Log.WriteToLog(LogSeverity.Info, downloadItem.ThreadID, string.Format("Processing HTML Started"), string.Format("{0}", downloadItem.Url));

            downloadItem.Result = new HtmlResult();

            downloadItem.Progress.Message = "Downloading " + downloadItem.Url;

            var cachePath = WebCache.GetPathFromUrl(downloadItem.Url, downloadItem.Section);

            Folders.CheckExists(cachePath, true);

            if (!downloadItem.IgnoreCache && !downloadItem.Url.Contains("YNoCache"))
            {
                if (File.Exists(cachePath + ".txt.gz"))
                {
                    Log.WriteToLog(LogSeverity.Info, downloadItem.ThreadID, string.Format(CultureInfo.CurrentCulture, "Url Found in Cache"), string.Format(CultureInfo.CurrentCulture, "{0}", downloadItem.Url));
                    downloadItem.Result = new HtmlResult
                    {
                        Result  = Gzip.Decompress(cachePath + ".txt.gz"),
                        Success = true
                    };

                    return;
                }
            }

            try
            {
                Log.WriteToLog(
                    LogSeverity.Info,
                    downloadItem.ThreadID,
                    string.Format(CultureInfo.CurrentCulture, "Downloading"),
                    string.Format(CultureInfo.CurrentCulture, "{0}", downloadItem.Url));

                downloadItem.Url = downloadItem.Url.Replace(" ", "+").Replace("%20", "+");

                var webClient = new WebClient
                {
                    Proxy = null
                };

                webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

                var outputString = webClient.DownloadString(downloadItem.Url);

                var encode = Encoding.GetEncoding(1252);
                if (downloadItem.Url.IndexOf("ofdb", StringComparison.CurrentCultureIgnoreCase) != -1 || downloadItem.Url.Contains("sratim") || downloadItem.Url.Contains("filmweb") || downloadItem.Url.Contains("allocine"))
                {
                    encode = Encoding.GetEncoding("UTF-8");
                }

                if (downloadItem.Url.Contains("filmaffinity") || downloadItem.Url.Contains("filmdelta"))
                {
                    encode = Encoding.GetEncoding("ISO-8859-1");
                }

                if (downloadItem.Url.Contains("kinopoisk"))
                {
                    encode = Encoding.GetEncoding("windows-1251");
                }

                Log.WriteToLog(
                    LogSeverity.Info,
                    downloadItem.ThreadID,
                    string.Format(CultureInfo.CurrentCulture, "Download Complete. Saving to Cache"),
                    string.Format(CultureInfo.CurrentCulture, "{0}", downloadItem.Url));

                File.WriteAllText(cachePath + ".txt.tmp", outputString, encode);

                Gzip.Compress(cachePath + ".txt.tmp", cachePath + ".txt.gz");
                File.Delete(cachePath + ".txt.tmp");

                Log.WriteToLog(
                    LogSeverity.Info,
                    downloadItem.ThreadID,
                    string.Format(CultureInfo.CurrentCulture, "Process Complete."),
                    string.Format(CultureInfo.CurrentCulture, "{0}", downloadItem.Url));

                downloadItem.Result.Result  = outputString;
                downloadItem.Result.Success = true;
                return;
            }
            catch (Exception ex)
            {
                Log.WriteToLog(LogSeverity.Error, LoggerName.GeneralLog, string.Format("Download Html {0}", downloadItem.Url), ex.Message);
                return;
            }
        }
Exemple #10
0
 /// <summary>
 /// 更新网站配置
 /// </summary>
 /// <param name="settings">网站配置实体</param>
 public static void SaveMasterSettings(SiteSettings settings)
 {
     saveMasterSettings(settings);
     WebCache.Remove("FileCache-MasterSettings");
 }
Exemple #11
0
        public void Load(DhtNetwork network)
        {
            // if the user has multiple ops, the lookup network is setup with the same settings
            // so it is easy to find and predictable for other's bootstrapping
            // we put it in local settings so we safe-guard these settings from moving to other computers
            // and having dupe dht lookup ids on the network
            try
            {
                var serializer = new XmlSerializer(typeof(PortsConfig));

                using (var reader = new StreamReader(PortsConfigPath))
                    Ports = (PortsConfig)serializer.Deserialize(reader);
            }
            catch
            {
                Ports = new PortsConfig();
            }

            if (Ports.UserID == 0 || network.Core.Sim != null)
            {
                Ports.UserID = Utilities.StrongRandUInt64(network.Core.StrongRndGen);
            }

            // keep tcp/udp the same by default
            if (Ports.Tcp == 0 || network.Core.Sim != null)
            {
                Ports.Tcp = (ushort)network.Core.RndGen.Next(3000, 15000);
            }

            if (Ports.Udp == 0 || network.Core.Sim != null)
            {
                Ports.Udp = Ports.Tcp;
            }


            // dont want instances saving and loading same lookup file
            if (network.Core.Sim == null && File.Exists(BootstrapPath))
            {
                try
                {
                    using (IVCryptoStream crypto = IVCryptoStream.Load(BootstrapPath, BootstrapKey))
                    {
                        PacketStream stream = new PacketStream(crypto, network.Protocol, FileAccess.Read);

                        G2Header root = null;

                        while (stream.ReadPacket(ref root))
                        {
                            if (root.Name == IdentityPacket.LookupCachedIP)
                            {
                                network.Cache.AddSavedContact(CachedIP.Decode(root));
                            }

                            if (root.Name == IdentityPacket.LookupCachedWeb)
                            {
                                network.Cache.AddWebCache(WebCache.Decode(root));
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    network.UpdateLog("Exception", "LookupSettings::Load " + ex.Message);
                }
            }
        }
Exemple #12
0
        public void Load(LoadModeType loadMode)
        {
            RijndaelManaged Password = new RijndaelManaged();

            Password.Key = PasswordKey;

            byte[] iv   = new byte[16];
            byte[] salt = new byte[4];

            OpCore lookup = null;

            if (Core != null)
            {
                lookup = Core.Context.Lookup;
            }

            try
            {
                using (TaggedStream file = new TaggedStream(ProfilePath, Protocol, ProcessSplash)) // tagged with splash
                {
                    // first 16 bytes IV, next 4 bytes is salt
                    file.Read(iv, 0, 16);
                    file.Read(salt, 0, 4);
                    Password.IV = iv;

                    using (CryptoStream crypto = new CryptoStream(file, Password.CreateDecryptor(), CryptoStreamMode.Read))
                    {
                        PacketStream stream = new PacketStream(crypto, Protocol, FileAccess.Read);

                        G2Header root = null;
                        while (stream.ReadPacket(ref root))
                        {
                            if (loadMode == LoadModeType.Settings)
                            {
                                if (root.Name == IdentityPacket.OperationSettings)
                                {
                                    Settings = SettingsPacket.Decode(root);
                                }

                                if (root.Name == IdentityPacket.UserInfo && Core != null &&
                                    (Core.Sim == null || !Core.Sim.Internet.FreshStart))
                                {
                                    Core.IndexInfo(UserInfo.Decode(root));
                                }

                                // save icon to identity file because only root node saves icon/splash to link file
                                // to minimize link file size, but allow user to set custom icon/splash if there are not overrides
                                if (root.Name == IdentityPacket.Icon)
                                {
                                    OpIcon = IconPacket.Decode(root).OpIcon;
                                }
                            }

                            if (lookup != null && (loadMode == LoadModeType.AllCaches || loadMode == LoadModeType.LookupCache))
                            {
                                if (root.Name == IdentityPacket.LookupCachedIP)
                                {
                                    lookup.Network.Cache.AddSavedContact(CachedIP.Decode(root));
                                }

                                if (root.Name == IdentityPacket.LookupCachedWeb)
                                {
                                    lookup.Network.Cache.AddWebCache(WebCache.Decode(root));
                                }
                            }

                            if (loadMode == LoadModeType.AllCaches)
                            {
                                if (root.Name == IdentityPacket.OpCachedIP)
                                {
                                    Core.Network.Cache.AddSavedContact(CachedIP.Decode(root));
                                }

                                if (root.Name == IdentityPacket.OpCachedWeb)
                                {
                                    Core.Network.Cache.AddWebCache(WebCache.Decode(root));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #13
0
        public void OnLoad(HttpContext context)
        {
            string msg = "";

            try
            {
                #region
                string email       = GetValue("phone");
                int    emailExists = viviapi.BLL.User.Factory.EmailExists(email);

                if (!string.IsNullOrEmpty(email))
                {
                    if (Validate.IsEmail(email))
                    {
                        if (emailExists == 999)
                        {
                            string cacheKey = string.Format(Constant.EmailRegCodeCacheKey, email);

                            string validcode = (string)WebCache.GetCacheService().RetrieveObject(cacheKey);
                            if (validcode == null)
                            {
                                //validcode = "1000".ToString(CultureInfo.InvariantCulture);
                                //WebCache.GetCacheService().AddObject(cacheKey, validcode);
                                //context.Response.ContentType = "text/plain";
                                //context.Response.Write("true");

                                validcode = new Random().Next(10000, 99999).ToString(CultureInfo.InvariantCulture);
                                WebCache.GetCacheService().AddObject(cacheKey, validcode);
                            }
                            string smscontext = Helper.GetRegCodeTemp();
                            if (!string.IsNullOrEmpty(smscontext))
                            {
                                smscontext = smscontext.Replace("{#regcode#}", validcode);
                                smscontext = smscontext.Replace("{#sitename#}",
                                                                viviapi.BLL.WebInfoFactory.CurrentWebInfo.Name);
                                smscontext = smscontext.Replace("{#sitename#}", viviapi.BLL.WebInfoFactory.CurrentWebInfo.Domain);
                            }

                            var emailcom = new EmailHelper(email
                                                           , email + "邮箱验证"
                                                           , smscontext
                                                           , true
                                                           , System.Text.Encoding.Default);
                            bool result = emailcom.Send();
                            if (result)
                            {
                                msg = "true";
                            }
                            else
                            {
                                msg = "邮件发送失败";
                            }
                        }

                        else if (emailExists == 1)
                        {
                            msg = "该邮箱正在审核";
                        }
                        else if (emailExists == 2)
                        {
                            msg = "该邮箱已注册";
                        }
                        else if (emailExists == 3)
                        {
                            msg = "该邮箱已被锁定";
                        }
                        else if (emailExists == 4)
                        {
                            msg = "您的邮箱审核失败";
                        }
                    }
                    else
                    {
                        msg = "请输入正确的手机号码";
                    }
                }
                else
                {
                    msg = "请输入手机号码";
                }
                #endregion
            }
            catch (Exception ex)
            {
                ExceptionHandler.HandleException(ex);
                msg = "error";
            }

            context.Response.ContentType = "text/plain";
            context.Response.Write(msg);
        }
Exemple #14
0
        private void CreateProductDataWidgets(PrinterSettings printerSettings, ProductSkuData product)
        {
            var row = new FlowLayoutWidget()
            {
                HAnchor = HAnchor.Stretch,
                Margin  = new BorderDouble(top: theme.DefaultContainerPadding)
            };

            productDataContainer.AddChild(row);

            var image = new ImageBuffer(150, 10);

            row.AddChild(new ImageWidget(image)
            {
                Margin  = new BorderDouble(right: theme.DefaultContainerPadding),
                VAnchor = VAnchor.Top
            });

            WebCache.RetrieveImageAsync(image, product.FeaturedImage.ImageUrl, scaleToImageX: true);

            var descriptionBackground = new GuiWidget()
            {
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Fit | VAnchor.Top,
                Padding = theme.DefaultContainerPadding
            };

            var description = new MarkdownWidget(theme)
            {
                MinimumSize = new VectorMath.Vector2(350, 0),
                HAnchor     = HAnchor.Stretch,
                VAnchor     = VAnchor.Fit,
                Markdown    = product.ProductDescription.Trim()
            };

            descriptionBackground.AddChild(description);
            descriptionBackground.BeforeDraw += (s, e) =>
            {
                var rect = new RoundedRect(descriptionBackground.LocalBounds, 3);
                e.Graphics2D.Render(rect, theme.SlightShade);
            };

            row.AddChild(descriptionBackground);

            var padding = theme.DefaultContainerPadding;

            var addonsColumn = new FlowLayoutWidget(FlowDirection.TopToBottom)
            {
                Padding = new BorderDouble(padding, padding, padding, 0),
                HAnchor = HAnchor.Stretch
            };

            var addonsSection = new SectionWidget("Upgrades and Accessories", addonsColumn, theme);

            productDataContainer.AddChild(addonsSection);
            theme.ApplyBoxStyle(addonsSection);
            addonsSection.Margin = addonsSection.Margin.Clone(left: 0);

            foreach (var item in product.ProductListing.AddOns)
            {
                var icon = new ImageBuffer(80, 0);
                WebCache.RetrieveImageAsync(icon, item.FeaturedImage.ImageUrl, scaleToImageX: true);

                var addOnRow = new AddOnRow(item.AddOnTitle, theme, null, icon)
                {
                    HAnchor = HAnchor.Stretch,
                    Cursor  = Cursors.Hand
                };

                foreach (var child in addOnRow.Children)
                {
                    child.Selectable = false;
                }

                addOnRow.Click += (s, e) =>
                {
                    ApplicationController.Instance.LaunchBrowser($"https://www.matterhackers.com/store/l/{item.AddOnListingReference}/sk/{item.AddOnSkuReference}");
                };

                addonsColumn.AddChild(addOnRow);
            }

            if (false)
            {
                var settingsPanel = new GuiWidget()
                {
                    HAnchor         = HAnchor.Stretch,
                    VAnchor         = VAnchor.Stretch,
                    MinimumSize     = new VectorMath.Vector2(20, 20),
                    DebugShowBounds = true
                };

                settingsPanel.Load += (s, e) =>
                {
                    var printer = new PrinterConfig(printerSettings);

                    var settingsContext = new SettingsContext(
                        printer,
                        null,
                        NamedSettingsLayers.All);

                    settingsPanel.AddChild(
                        new ConfigurePrinterWidget(settingsContext, printer, theme)
                    {
                        HAnchor = HAnchor.Stretch,
                        VAnchor = VAnchor.Stretch,
                    });
                };

                this.AddChild(new SectionWidget("Settings", settingsPanel, theme, expanded: false, setContentVAnchor: false)
                {
                    VAnchor = VAnchor.Stretch
                });
            }
        }
Exemple #15
0
        public ActionResult Search(string text)
        {
            Session["text"]     = text;
            Session["category"] = false;
            SearchResponse result       = new SearchResponse();
            SearchResponse returnResult = new SearchResponse();

            result = WebCache.Get("searchResponse" + text);
            if (result == null)
            {
                result = new SearchResponse();

                XmlSerializer serializer = new XmlSerializer(typeof(SearchResponse));

                int       nextStartPosition = 0;
                Content[] storeContents     = new Content[0];
                decimal   pages             = 0;

                HttpWebRequest request = WebRequest.Create("http://openweb-stg.nlb.gov.sg/REST/SM2/contents/search?tags=" + text + "&max=30&start=1") as HttpWebRequest;
                request.Headers.Add("X-Authorization", "Q2hyaXN0b3BoZXJLaG9vU29vR3VhbjpDaHIhc2kwcGhAUmswOTg=");
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    result        = serializer.Deserialize(reader) as SearchResponse;
                    storeContents = result.Contents;

                    foreach (Content c in storeContents)
                    {
                        string desc = c.Desc;
                        IEnumerable <Record> contain = CategoryMappings.Records.Where(x => desc.Contains(x.Keyword));
                        foreach (Record r in contain)
                        {
                            if (result.Statistics.ContainsKey(r.Category))
                            {
                                if (!result.statisticsId.ContainsKey(c.Id + "|" + r.Category))
                                {
                                    result.Statistics[r.Category] += 1;
                                    result.statisticsId.Add(c.Id + "|" + r.Category, r);
                                }
                            }
                        }
                    }
                }

                if (result.TotalRecords > 0)
                {
                    pages             = Decimal.Ceiling(Convert.ToDecimal(result.TotalRecords) / 30);
                    nextStartPosition = 31;
                }

                for (int i = 1; i < pages; i++)
                {
                    request = WebRequest.Create("http://openweb-stg.nlb.gov.sg/REST/SM2/contents/search?tags=" + text + "&max=30&start=" + nextStartPosition) as HttpWebRequest;
                    request.Headers.Add("X-Authorization", "Q2hyaXN0b3BoZXJLaG9vU29vR3VhbjpDaHIhc2kwcGhAUmswOTg=");
                    response = request.GetResponse() as HttpWebResponse;
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        result        = serializer.Deserialize(reader) as SearchResponse;
                        storeContents = storeContents.Union(result.Contents).ToArray();

                        foreach (Content c in storeContents)
                        {
                            string desc = c.Desc;
                            IEnumerable <Record> contain = CategoryMappings.Records.Where(x => desc.Contains(x.Keyword));
                            foreach (Record r in contain)
                            {
                                if (result.Statistics.ContainsKey(r.Category))
                                {
                                    if (!result.statisticsId.ContainsKey(c.Id + "|" + r.Category))
                                    {
                                        result.Statistics[r.Category] += 1;
                                        result.statisticsId.Add(c.Id + "|" + r.Category, r);
                                    }
                                }
                            }
                        }
                    }

                    nextStartPosition += 30;
                }


                result.Contents = storeContents;

                WebCache.Set("searchResponse" + text, result, 120);
            }

            returnResult.StartPosition   = 1;
            returnResult.CurrentPosition = 1;
            returnResult.TotalRecords    = result.TotalRecords;
            Content[] returnContents = new Content[10];
            if (returnResult.TotalRecords < 10)
            {
                returnContents = new Content[returnResult.TotalRecords];
            }
            for (int i = 0; i < returnContents.Length; i++)
            {
                returnContents[i] = result.Contents[i];
            }
            returnResult.Contents = returnContents;


            return(PartialView(returnResult));
        }