Exemple #1
1
 public static ActionResult Alert(this Controller controller, string message)
 {
     string str = string.Format("wAlert('{0}')", message);
     JavaScriptResult result = new JavaScriptResult();
     result.Script = str;
     return result;
 }
        private static JavaScriptResult CreateResourceScript(string pageName)
        {
            string sResxPath = CustomLocalizationUtility.GetResourceFilePath(pageName,
                                            Convert.ToString(HttpContext.Current.Session["CurrentCulture"]));

            var resourceData = CustomLocalizationUtility.GetResourceData(sResxPath, pageName);

            StringBuilder sb = new StringBuilder();
            //sb.Append(pageName);
            sb.Append(string.Format("{0}",pageName));
            sb.Append("={");
            foreach (var resource in resourceData)
            {

                sb.AppendFormat("\"{0}\":\"{1}\",", resource.Key, EncodeValue(resource.NewValue));
            }

            string script = sb.ToString();
            if (!string.IsNullOrEmpty(script))
                script = script.Remove(script.Length - 1);

            script += "};";

            JavaScriptResult result = new JavaScriptResult { Script = script };
            return result;
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                if ((!filterContext.HttpContext.Request.IsAuthenticated) || (HttpContext.Current.Session["UsuarioGP"] == null))
                {
                    JavaScriptResult result = new JavaScriptResult()
                    {
                        Script = "window.location='" + "/Account/Login" + "';"
                    };
                    filterContext.Result = result;
                }
            }
            else
            {
                if (!filterContext.HttpContext.Request.IsAuthenticated || (HttpContext.Current.Session["UsuarioGP"] == null))
                {

                    filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary(new
                        {
                            controller = "Account",
                            action = "Login"
                        }
                    ));
                }
            }

            base.OnActionExecuting(filterContext);
        }
        public ActionResult logOn(LogOnModel model, string returnUrl)
        {

            if (ModelState.IsValid)
            {

                if (model.UserName=="abs" && model.Password=="abs")
                {

                    FormsAuthentication.Initialize();
                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, model.UserName, DateTime.Now, DateTime.Now.AddMinutes(30), model.RememberMe, FormsAuthentication.FormsCookiePath);
                    string hash = FormsAuthentication.Encrypt(ticket);
                    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
                    if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
                    Response.Cookies.Add(cookie);
                    if ((!String.IsNullOrEmpty(returnUrl)) && returnUrl.Length > 1)
                        return Redirect(returnUrl);
                    else
                    {
                        //return RedirectToAction("Grid", "Popup");

                        JavaScriptResult js = new JavaScriptResult();
                        js.Script = "gotoGrid();";
                        return js;
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Incorrect user name or password.");
                }
            }

            // If we got this far, something failed, redisplay form
            return PartialView("LogOn", model);
        }
 /// <summary>
 /// The JSON response.
 /// </summary>
 /// <returns>
 /// The <see cref="ActionResult"/>.
 /// </returns>
 public ActionResult JsonP()
 {
     var result = new JavaScriptResult
                      {
                          Script =
                              string.Format("parseJson({{serverTime: '{0}'}});", DateTime.Now)
                      };
     return result;
 }
        public TaconiteResult Execute(JavaScriptResult javaScriptResult)
        {
            if (javaScriptResult == null)
            throw new ArgumentNullException("javaScriptResult");

              var command = new EvalCommand(javaScriptResult);
              AddCommand(command);

              return this;
        }
        public void Equals_OtherEvalCommandHasDifferentJavaScriptResult_ReturnsFalse()
        {
            var javaScriptResult0 = new JavaScriptResult();
              var javaScriptResult1 = new JavaScriptResult();
              var evalCommand0 = new EvalCommand(javaScriptResult0);
              var evalCommand1 = new EvalCommand(javaScriptResult1);

              var result = evalCommand0.Equals(evalCommand1);

              result.Should().BeFalse();
        }
        public void Equals_OneEvalCommandHasScriptAndOtherHasJavaScriptResult_ReturnsFalse()
        {
            var script = "console.log('weeeeeee')";
              var javaScriptResult = new JavaScriptResult();
              var evalCommand0 = new EvalCommand(script);
              var evalCommand1 = new EvalCommand(javaScriptResult);

              var result = evalCommand0.Equals(evalCommand1);

              result.Should().BeFalse();
        }
 public override void ExecuteResult(ControllerContext context)
 {
     if (context.RequestContext.HttpContext.Request.IsAjaxRequest())
     {
         string destinationUrl = UrlHelper.GenerateContentUrl(Url, context.HttpContext);
         JavaScriptResult result = new JavaScriptResult()
         {
             Script = "window.location='" + destinationUrl + "';"
         };
         result.ExecuteResult(context);
     }
     else
         base.ExecuteResult(context);
 }
        public void CreateCommandXElement_JavaScriptResult_ReturnsCorrectXElement()
        {
            var javaScriptResult = new JavaScriptResult();
              var evalCommand = new EvalCommand(javaScriptResult);
              var controllerContext = Substitute.For<ControllerContext>();
              var script = "console.log('weeeeeee')";
              var actionResultExecutor = Substitute.For<ActionResultExecutor>(controllerContext);
              actionResultExecutor.Execute(javaScriptResult).Returns(script);

              var result = evalCommand.CreateCommandXElement(actionResultExecutor);

              result.Name.Should().Be((XName)"eval");
              result.Value.Should().Be(script);
        }
        public void ExecuteJavaScriptResult()
        {
            var javaScriptResult = new JavaScriptResult();

              var result = Taconite.Execute(javaScriptResult);

              result.Commands.Should().HaveCount(1);
              var command = result.Commands.Single();
              command.As<EvalCommand>()
            .Should().NotBeNull()
            .ShouldHave().SharedProperties().EqualTo(new
              {
            Script = (string) null,
            JavaScriptResult = javaScriptResult
              });
        }
Exemple #12
0
        public JavaScriptResult GoogleAnalytics()
        {
            HNKBlogConfigManager cfgMgr = null;
            try
            {
                cfgMgr = new HNKBlogConfigManager(AppSettings.GetDbConnectionString());
            }
            catch (Exception e)
            {
                AzureLog.WriteToTable(e);
                return new JavaScriptResult();
            }

            JavaScriptResult jsResult = new JavaScriptResult();
            jsResult.Script = cfgMgr.GoogleAnalytics.Value;
            return jsResult;
        }
        public static ActionResult Redirect(RouteValueDictionary route, ActionExecutingContext context)
        {
            ActionResult result;

            if (context.HttpContext.Request.IsAjaxRequest())
            {
                UrlHelper url = new UrlHelper(context.RequestContext);

                result = new JavaScriptResult()
                {
                    Script = "window.location = '" + url.Action(null, route) + "';"
                };
            }
            else
            {
                result = new RedirectToRouteResult(route);
            }

            return result;
        }
 /// <summary>
 /// Returns GEOIP data for a given IP address.
 /// </summary>
 /// <remarks>While technically this is not data in the analysys portion of the database it is related</remarks>
 /// <param name="ip">a string that is parsable into an ip address</param>
 /// <returns>any location information that can be found for the ip address or null if no entry was found.</returns>
 public ActionResult Location(string ip)
 {
     var result = new JavaScriptResult();
     var dbPath = Server.MapPath(ConfigurationManager.ConnectionStrings["geoip"].ConnectionString);
     if (System.IO.File.Exists(dbPath))
     {
         var ls = new MaxMind.GeoIP.LookupService(dbPath, MaxMind.GeoIP.LookupService.GEOIP_STANDARD);
         MaxMind.GeoIP.Location loc;
         if (!ip.StartsWith("10."))
             loc = ls.getLocation(System.Net.IPAddress.Parse(ip));
         else
             loc = new MaxMind.GeoIP.Location() { countryName = "US", countryCode = "US", city = "LAN", regionName = "Internal Address" };
         if (loc != null)
             result.Script = "{" + string.Format("areaCode:{0}, city:'{1}', countryCode:'{2}', countryName:'{3}', latitude:{4}, longitude:{5}, metroCode:{6}, postalCode:'{7}', region:'{8}', regionName:'{9}'",
                 loc.area_code, loc.city, loc.countryCode, loc.countryName, loc.latitude, loc.longitude, loc.metro_code, loc.postalCode, loc.region, loc.regionName) + "}";
         else
             result.Script = "{}";
     }
     else
         result.Script = "{}";
     return result;
 }
        public void Equals_OtherEvalCommandHasSameJavaScriptResult_ReturnsTrue()
        {
            var javaScriptResult = new JavaScriptResult();
              var evalCommand0 = new EvalCommand(javaScriptResult);
              var evalCommand1 = new EvalCommand(javaScriptResult);

              var result = evalCommand0.Equals(evalCommand1);

              result.Should().BeTrue();
        }
        /// <summary>
        /// This method is used to call external web services from the client side.
        /// We need to use a proxy due to cross-site scripting issues.
        /// NOTE: if you can use JSONP instead, use that instead of the proxy
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public ActionResult ServiceProxy(string url)
        {
            WebRequest request = WebRequest.Create(url);
            WebResponse response = request.GetResponse();

            using (StreamReader responseStream = new StreamReader(response.GetResponseStream()))
            {
                string responseText = responseStream.ReadToEnd();

                JavaScriptResult result = new JavaScriptResult();
                result.Script = responseText;

                return result;
            }
        }
        public ActionResult LogOnAsync(LogOnModel model, string returnUrl)
        {
            string errorMessage = null;
            if (ModelState.IsValid && _webSecurity.Login(model.UserName, model.Password, model.RememberMe))
            {
                if (StoreHelper.IsUserAuthorized(model.UserName, out errorMessage))
                {
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        UserHelper.OnPostLogon(model.UserName);
                        return Redirect(returnUrl);
                    }
                    var res = new JavaScriptResult { Script = "location.reload();" };
                    return res;
                }
            }

            // If we got this far, something failed, redisplay form
            ModelState.AddModelError("", string.IsNullOrEmpty(errorMessage) ? "The user name or password provided is incorrect." : errorMessage);
            return PartialView(model);
        }
        /// <summary>
        /// Returns the data on record for a given URL at a specific time
        /// </summary>
        /// <param name="d">An integer in the format of 2011013023 (YYYY MM DD HH)</param>
        /// <param name="p">the hostname and path to a page (no query string).</param>
        /// <param name="h">number of hours of data to include</param>
        /// <returns>The page analysis record for the given page.</returns>
        public ActionResult PageViews(int? d, string p, int h=1)
        {
            // our database size contrains the number of samples we can hold.
            if (h < 1 || h > 480)
                throw new ArgumentOutOfRangeException("h");
            // if no value is passed in then we want to use a sample from 10 minutes ago
            // (solves an issue where there may be no data for the current hour in each
            // minute upto 10 minutes past the hour (NOTE: based on 10 min M/R schedule)
            DateTime dDate;
            if (!d.HasValue || !DateTime.TryParseExact(d.ToString(), "yyyyMMddHH", CultureInfo.CurrentCulture, DateTimeStyles.AssumeUniversal, out dDate))
                dDate = DateTime.UtcNow.AddMinutes(-10);

            var js = new JavaScriptResult();
            MongoServer server = MongoServer.Create(ConfigurationManager.ConnectionStrings["mongodb"].ConnectionString);
            var pages = server.GetDatabase("analysis").GetCollection("pages");

            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            for (int i = 0; i < h; i++)
            {
                var pageData = pages.FindOne(Query.EQ("_id", String.Format("{0}:{1}", dDate.ToString("yyyyMMddHH"), p)));
                if (pageData != null)
                    sb.Append(pageData.ToString().Replace("ObjectId(", "").Replace("),", ",").Replace("ISODate(", ""));
                else
                {
                    sb.Append("{ ");
                    sb.AppendFormat("\"_id\" : \"{0}:{1}", dDate.ToString("yyyy-MM-ddTHH"), p);
                    sb.Append("\", \"value\" : { ");
                    sb.AppendFormat("\"dateLow\" : \"{0}:00:00Z\", \"dateHigh\" : \"{0}:59:59Z\", \"host\" : \"{1}\", ", dDate.ToString("yyyy-MM-ddTHH"), p.Substring(0, (p.IndexOf('/') > 0 ? p.IndexOf('/') : p.Length)));
                    sb.Append("\"views\" : 0, \"method\" : { }, \"referer\" : {  }, \"keywords\" : { }, \"mime\" : \"n/a\", \"latency\" : { \"avg\" : 0, \"count\" : 0, \"min\" : 0, \"max\" : 0 } } }");
                }
                if (i < (h - 1))
                    sb.Append(","); // separator
                dDate = dDate.AddHours(-1);
            }
            sb.Append("]");
            js.Script = sb.ToString();
            return js;
        }
Exemple #19
0
 /// <summary>
 /// Executes JavaScript.
 /// </summary>
 public static TaconiteMvc.TaconiteResult Execute(System.Web.Mvc.JavaScriptResult javaScriptResult)
 {
     return((new TaconiteResult()).Execute(javaScriptResult));
 }
Exemple #20
0
 public JavaScriptResult ClientScript()
 {
     var r = new JavaScriptResult();
     r.Script = System.IO.File.ReadAllText(Server.MapPath("~/scripts/canary.js"));
     return r;
 }
 //public ActionResult fileResult() {
 //    return result;
 //}
 public ActionResult jsResult()
 {
     JavaScriptResult result = new JavaScriptResult();
     result.Script = "alert('js')";
     return result;
 }
 public JavaScriptResult Proxy(string type, string assbemly)
 {
     Type sType = ReflectionHelper.GetType(type, assbemly);
     var result=new  JavaScriptResult();
     result.Script= AjaxServiceProxy.GetProxyScript(sType);
     return result;
 }
Exemple #23
0
 public ActionResult UrlLogin(string loginname, string urllogin)
 {
     LoginUserBLL bll = new LoginUserBLL();
     if (bll.Login(loginname))
     {
         //登录成功,跳转到主页面
         return Redirect("~/Home/Index?urllogin="******"alert('业务系统未找到[" + loginname + "]登录人!')";
         return js;
     }
 }
        public void GetHashCode_EvalCommandHasScriptAndOtherHasJavaScriptResult_ReturnsDifferentHashCodes()
        {
            var script = "console.log('weeeeeee')";
              var javaScriptResult = new JavaScriptResult();
              var evalCommand0 = new EvalCommand(script);
              var evalCommand1 = new EvalCommand(javaScriptResult);

              var result0 = evalCommand0.GetHashCode();
              var result1 = evalCommand1.GetHashCode();

              result0.Should().NotBe(result1);
        }
        public void GetHashCode_EvalCommandsHaveDifferentJavaScriptResults_ReturnsDifferentHashCodes()
        {
            var javaScriptResult0 = new JavaScriptResult();
              var javaScriptResult1 = new JavaScriptResult();
              var evalCommand0 = new EvalCommand(javaScriptResult0);
              var evalCommand1 = new EvalCommand(javaScriptResult1);

              var result0 = evalCommand0.GetHashCode();
              var result1 = evalCommand1.GetHashCode();

              result0.Should().NotBe(result1);
        }
 /// <summary>
 /// Creates a new <see cref="EvalCommand"/>.
 /// </summary>
 /// <param name="javaScriptResult">The <see cref="JavaScriptResult"/> to execute.</param>
 public EvalCommand(JavaScriptResult javaScriptResult)
 {
     _javaScriptResult = javaScriptResult;
 }
        public void GetHashCode_EvalCommandsHaveSameJavaScriptResult_ReturnsSameHashCode()
        {
            var javaScriptResult = new JavaScriptResult();
              var evalCommand0 = new EvalCommand(javaScriptResult);
              var evalCommand1 = new EvalCommand(javaScriptResult);

              var result0 = evalCommand0.GetHashCode();
              var result1 = evalCommand1.GetHashCode();

              result0.Should().Be(result1);
        }