Esempio n. 1
0
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(Navigator.GetUrlFromKey(navigatorId));
            HttpServerUtility s = HttpContext.Current.Server;

            if (parameters.Count > 0)
            {
                sb.Append("?");//todo: url might already have a 1st item. don't assume
                bool isFirst = true;
                foreach (string key in parameters.Keys)
                {
                    if (isFirst == false)
                    {
                        sb.Append("&");
                    }

                    isFirst = false;
                    sb.AppendFormat("{0}={1}", s.UrlEncode(key), s.UrlEncode(parameters[key]));
                }
            }

            return(sb.ToString());
        }
Esempio n. 2
0
        /// <summary>
        /// 输出结果
        /// </summary>
        /// <param name="url">上传之后文件的完整路径</param>
        /// <param name="SaveMethod">保存方法</param>
        /// <param name="errMsg">错误信息</param>
        protected virtual void ResultOutput(string url, FU_SaveMethod SaveMethod, string errMsg)
        {
            url = url.Replace("//", "/");
            url = config.PerUrl + url;
            string json = string.Format("{{iSuccess:{0},msg:\"{1}\",url:\"{2}\",method:\"{3}\"}}",
                                        (SaveMethod == FU_SaveMethod.fail ? 0 : 1), jsEncode(errMsg), jsEncode(url), SaveMethod);
            string ret = config.Return;

            if (config.returnMode == FUC_RETURN.redirect)
            {
                ret = ret.Replace("{fileUrl}", Server.UrlEncode(url));
                ret = ret.Replace("{json}", Server.UrlEncode(json));
                ret = ret.Replace("{msg}", Server.UrlEncode(errMsg));
                ret = ret.Replace("{method}", Server.UrlEncode(SaveMethod.ToString()));
                Response.Redirect(ret);
            }
            else
            {
                ret = ret.Replace("{fileUrl}", url);
                ret = ret.Replace("{json}", json);
                ret = ret.Replace("{msg}", errMsg);
                ret = ret.Replace("{method}", SaveMethod.ToString());
                Response.Write(ret);
            }
        }
Esempio n. 3
0
        public override string ToString()
        {
            // Build the query string.
            // The name and value are separated with the = character.
            // Each subsequent name/value pair is separated with the & character.
            // To ensure that the setting value doesn't already use
            // the & or = characters (which would then be mistaken for a delimiter)
            // this code encodes the name and value before putting
            // it into the string.
            HttpServerUtility server = HttpContext.Current.Server;
            StringBuilder     sb     = new StringBuilder();

            foreach (DictionaryEntry item in this)
            {
                sb.Append(server.UrlEncode(item.Key.ToString()));
                sb.Append("=");
                sb.Append(server.UrlEncode(item.Value.ToString()));
                sb.Append("&");
            }

            // Remove the last &.
            sb.Remove(sb.Length - 1, 1);

            // Perform the encryption.
            byte[] encryptedData = EncryptionUtil.EncryptString(sb.ToString(), crypt);

            // Convert the encrypted byte array to a URL-legal string.
            // This would also be a good place to check that the data isn't too large
            // to fit in a typical 4 KB query string.
            return(HexEncoding.ToString(encryptedData));
        }
        public NameValueCollection SetExpressCheckoutDG(string paymentAmount, string currencyCodeType, string paymentType, string returnURL, string cancelURL, List <PayPalItem> items, string customField, bool payByCreditCard, string itemCategory)
        {
            HttpServerUtility   server = HttpContext.Current.Server;
            NameValueCollection nvpstr = new NameValueCollection();

            nvpstr["PAYMENTREQUEST_0_AMT"]           = server.UrlEncode(paymentAmount);
            nvpstr["PAYMENTREQUEST_0_PAYMENTACTION"] = server.UrlEncode(paymentType);
            nvpstr["RETURNURL"] = returnURL;
            nvpstr["CANCELURL"] = cancelURL;
            nvpstr["PAYMENTREQUEST_0_CURRENCYCODE"] = server.UrlEncode(currencyCodeType);
            nvpstr["REQCONFIRMSHIPPING"]            = "0";
            nvpstr["NOSHIPPING"] = "1";
            nvpstr["PAYMENTREQUEST_0_CUSTOM"] = customField;
            nvpstr["PAGESTYLE"] = pageStyle;

            if (payByCreditCard)
            {
                nvpstr["SOLUTIONTYPE"] = "Sole";
                nvpstr["LANDINGPAGE"]  = "Billing";
            }

            for (int i = 0; i < items.Count; i++)
            {
                nvpstr["L_PAYMENTREQUEST_0_NAME" + i.ToString()]         = items[i].name;
                nvpstr["L_PAYMENTREQUEST_0_AMT" + i.ToString()]          = server.UrlEncode(items[i].amt);
                nvpstr["L_PAYMENTREQUEST_0_QTY" + i.ToString()]          = server.UrlEncode(items[i].qty);
                nvpstr["L_PAYMENTREQUEST_0_ITEMCATEGORY" + i.ToString()] = itemCategory;
            }

            /*
             *      string nvpstr = "&PAYMENTREQUEST_0_AMT=" + paymentAmount;
             *      nvpstr += "&PAYMENTREQUEST_0_PAYMENTACTION=" + paymentType;
             *      nvpstr += "&RETURNURL=" + returnURL;
             *      nvpstr += "&CANCELURL=" + cancelURL;
             *      nvpstr += "&PAYMENTREQUEST_0_CURRENCYCODE=" + currencyCodeType;
             *      nvpstr += "&REQCONFIRMSHIPPING=0";
             *      nvpstr += "&NOSHIPPING=1";
             *      nvpstr += "&PAYMENTREQUEST_0_CUSTOM=" + trackId;
             *
             * for(int i = 0; i < items.Count; i++)
             * {
             *              nvpstr += "&L_PAYMENTREQUEST_0_NAME" + i.ToString() + "=" + server.UrlEncode(items[i].name);
             *              nvpstr += "&L_PAYMENTREQUEST_0_AMT" + i.ToString() + "=" + server.UrlEncode(items[i].amt);
             *              nvpstr += "&L_PAYMENTREQUEST_0_QTY" + i.ToString() + "=" + server.UrlEncode(items[i].qty);
             *              nvpstr += "&L_PAYMENTREQUEST_0_ITEMCATEGORY" + i.ToString() + "=Physical";
             * }
             */

            NameValueCollection result = hashCall("SetExpressCheckout", nvpstr);
            string ack = result.GetValues("ACK").First();

            ack = ack.ToUpper();
            if (ack == "SUCCESS" || ack == "SUCCESSWITHWARNING")
            {
                token = result.GetValues("TOKEN").First();
            }

            return(result);
        }
Esempio n. 5
0
	public void CheckSecurity(int iLevel) {
		if (Session["UserID"] == null || Session["UserID"].ToString().Length == 0) {
			Response.Redirect("Login.aspx?QueryString=" + Server.UrlEncode(Request.ServerVariables["QUERY_STRING"]) + "&ret_page=" + Server.UrlEncode(Request.ServerVariables["SCRIPT_NAME"]));
		} else {
			if (Int16.Parse(Session["UserRights"].ToString()) < iLevel)
				Response.Redirect("Login.aspx?QueryString=" + Server.UrlEncode(Request.ServerVariables["QUERY_STRING"]) + "&ret_page=" + Server.UrlEncode(Request.ServerVariables["SCRIPT_NAME"])) ;
		}
	}
Esempio n. 6
0
        public string GetQueryByParameterList(Dictionary <string, string> parameters, HttpServerUtility server)
        {
            string query = string.Empty;

            foreach (KeyValuePair <string, string> item in parameters)
            {
                query += "&" + server.UrlEncode(item.Key) + "=" + server.UrlEncode(item.Value);
            }
            return(query.TrimStart('&'));
        }
Esempio n. 7
0
        public static void SetCookie(String key, String valueString)
        {
            HttpServerUtility serverUtility = HttpContext.Current.Server;

            key         = serverUtility.UrlEncode(key);
            valueString = serverUtility.UrlEncode(valueString);

            HttpCookie cookie = new HttpCookie(key, valueString);

            SetCookie(cookie);
        }
Esempio n. 8
0
        public static void ListSubscribe(string email_address, string first, string last)
        {
            HttpServerUtility server = HttpContext.Current.Server;


            string parameters = "apikey=" + apiKey + "&id=" + listId + "&double_optin=false&update_existing=false&replace_interests=false&send_welcome=true";

            parameters += "&email[email]=" + server.UrlEncode(email_address);
            parameters += "&merge_vars[FNAME]=" + server.UrlEncode(first);
            parameters += "&merge_vars[LNAME]=" + server.UrlEncode(last);

            XmlDocument xmlDocument = Invoke("lists", "subscribe", parameters);
        }
Esempio n. 9
0
        /// <summary>
        /// 获取带令牌请求的URL
        /// 在当前URL中附加上令牌请求参数
        /// </summary>
        /// <returns></returns>
        private string getTokenURL()
        {
            string url = System.Web.HttpContext.Current.Request.Url.AbsoluteUri;
            Regex  reg = new Regex(@"^.*\?.+=.+$");

            if (reg.IsMatch(url))
            {
                url += "&Token=$Token$";
            }
            else
            {
                url += "?Token=$Token$";
            }
            return(getTokenUri + Server.UrlEncode(url));
        }
Esempio n. 10
0
 private void SendURL()
 {
     if (session.IsNewSession)
     {
         StringBuilder url  = new StringBuilder(request.Url.ToString());
         String[]      keys = request.QueryString.AllKeys;
         if (keys.Length > 0)
         {
             url.Append('?');
             foreach (String key in keys)
             {
                 if (!key.ToLower().StartsWith("phprpc_"))
                 {
                     String[] values = request.QueryString.GetValues(key);
                     for (Int32 i = 0, n = values.Length; i < n; i++)
                     {
                         url.Append(key).Append('=').Append(server.UrlEncode(values[i])).Append('&');
                     }
                 }
             }
             url.Length--;
         }
         buffer.Append("phprpc_url=\"");
         buffer.Append(EncodeString(response.ApplyAppPathModifier(url.ToString())));
         buffer.Append("\";\r\n");
     }
 }
Esempio n. 11
0
    private void EnviarMensajeUsuario(string EmailUsuario)
    {
        string validationCode = new Random().Next().ToString();

        //1.-Destino del mensaje
        System.Net.Mail.MailAddressCollection MisDestinos = new System.Net.Mail.MailAddressCollection();
        MisDestinos.Add(new System.Net.Mail.MailAddress(EmailUsuario));

        //2.-Cuerpo del mensaje
        HttpServerUtility server   = HttpContext.Current.Server;
        string            sMensaje = "We have sucessfully received your registration request to DropKeys. To complete the subscription process, please click the following link :\r\n\r\n " + Request.Url.GetLeftPart(UriPartial.Authority) + "/validatecode.aspx?email=" +
                                     server.UrlEncode(EmailUsuario) + "&vc=" + validationCode + "\r\n\r\nThank you.";

        if (EmailUtils.SendMessageEmail(MisDestinos, "Verify your email", sMensaje))
        {
            using (Clases.cASPNET_INFO_USUARIO objUsuario = new Clases.cASPNET_INFO_USUARIO())
            {
                MembershipUser Usuario = Membership.GetUser(EmailUsuario, false);
                objUsuario.userid = Convert.ToInt32(Usuario.ProviderUserKey);
                if (objUsuario.bConsultar())
                {
                    objUsuario.mensaje_validacion = true;
                    objUsuario.validado           = false;
                    objUsuario.codigo_validacion  = validationCode;
                    objUsuario.bModificar();
                }
            }
        }
    }
Esempio n. 12
0
        /// <summary>
        /// Take a comma-separated length of text and create links from it
        /// </summary>
        /// <param name="server">An <see cref="HttpServerUtility"/> for context information</param>
        /// <param name="stringCsvList">The comma-separated list of strings</param>
        /// <param name="urlFormat">a string.Format where {0} will be replaced with the search
        /// terms</param>
        /// <returns>A string containing search links to each of the comma-separated search values
        /// </returns>
        private string CreateSearchLinks(HttpServerUtility server,
                                         string stringCsvList,
                                         string urlFormat)
        {
            string[] items;
            if (stringCsvList.Contains(','))
            {
                items = stringCsvList.Split(',');
            }
            else
            {
                items = new string[1] {
                    stringCsvList
                };
            }

            StringBuilder stringWithLinks = null;

            foreach (string stringItem in items)
            {
                string link = string.Format(urlFormat, server.UrlEncode(stringItem.Trim()));
                if (stringWithLinks != null)
                {
                    stringWithLinks.Append(", ");
                }
                else
                {
                    stringWithLinks = new StringBuilder();
                }
                stringWithLinks.AppendFormat("<a href=\"{0}\" target=\"_blank\">{1} <small><span class=\"glyphicon glyphicon-new-window\"></span></small></a>",
                                             VirtualPathUtility.ToAbsolute(link),
                                             stringItem.Trim());
            }
            return(stringWithLinks.ToString());
        }
Esempio n. 13
0
        public static bool ListUpdateMember(string email, string tag, DateTime?value)
        {
            HttpServerUtility server = HttpContext.Current.Server;

            string parameters = "apikey=" + apiKey + "&id=" + listId;

            parameters += "&email[email]=" + email;
            if (value.HasValue)
            {
                parameters += "&merge_vars[" + tag + "]=" + server.UrlEncode(value.Value.ToString("yyyy-MM-dd"));
            }
            else
            {
                parameters += "&merge_vars[" + tag + "]=";
            }

            XmlDocument xmlDocument = Invoke("lists", "update-member", parameters);
            XmlNodeList ErrorList   = xmlDocument.SelectNodes("MCAPI/error");

            if (ErrorList.Count == 0)
            {
                return(true);
            }
            else
            {
                XmlNode error = ErrorList[0];
                return(false);
            }
        }
Esempio n. 14
0
 public static void LoginCheck(HttpSessionState session, HttpRequest request, HttpResponse response,
                               HttpServerUtility server)
 {
     if (session["user"] == null)
     {
         response.Redirect("~/Login.aspx?pre=" + server.UrlEncode(request.Url.AbsoluteUri));
     }
 }
Esempio n. 15
0
        public static void Setting_Redirect(HttpRequest Request, HttpSessionState Session, HttpResponse Response, HttpServerUtility Server)
        {
            try
            {
                //页面初始载入判断是否已存登录用户
                if (string.IsNullOrEmpty(Request["code"]))
                {
                    //用户未登录,通过oauth授权去钉钉服务器拿取授权

                    //去拿授权成功后带着code与state的回调地址,可以是当前项目中的任意其它地址,这里使用当前页面
                    string redirecturi = Server.UrlEncode(Config.WebUrl + Config.ServerUri);


                    //state 在 oauth中是为了随止跨站攻击的,所以回调之后一定要比较回调来的state与这个session["state]是否相等
                    //具体的是什么原理可以参考oauth中关于state的介绍
                    string state = Helper.state();
                    Session["state"] = state;
                    //这里的含义是说,我当前的网站没登录,我带着我的合法的认证(Config.SCorpId)去钉钉要一个当前登录用户分配的code,拿到这个code可以去换取当前的用户信息,来实现免登
                    string url = Connect_Flg + Config.ECorpId + "&redirect_uri=" + redirecturi + "&response_type=code&scope=snsapi_base&state=" + state;
                    Response.Redirect(url);
                }
                else if (!string.IsNullOrEmpty(Request["code"]))
                {
                    //钉钉服务器根据上面的回调地址回传了code与state

                    /*
                     *
                     * code的用途是配合AccessToken去换取用户的信息,这样可以做到免登
                     * code只允许使用一次
                     * code应该也有有效期,但在官方文档中暂未看到说明;
                     * 建议拿到code后就去换取用户实现免登
                     *
                     *
                     * */
                    string code  = Request["code"].ToString();
                    string state = Request["state"].ToString();

                    //判断来源是否有效,是否是跨站
                    if (Session["state"].ToString() == state)
                    {
                    }
                    else
                    {
                        LogHelper.Info("无效的访问");
                    }

                    ////在日志中打印code查看参数是否接收到
                    //Helper.WriteLog("code:" + code);

                    Response.Redirect(Config.ServerUri + "?code=" + code);
                }
            }
            catch (Exception ex)
            {
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Converts a <see cref="NameValueCollection"/> query string to a flat string.
        /// </summary>
        /// <param name="qs">The query string to convert.</param>
        /// <param name="server">An <see cref="HttpServerUtility"/> instance to perform URL-encoding.</param>
        /// <returns>The flattened string equivalent of the query string.</returns>
        public static string ToQueryString(this NameValueCollection qs, HttpServerUtility server = null)
        {
            StringBuilder sb = new StringBuilder();

            foreach (string key in qs.AllKeys)
            {
                sb.AppendFormat("&{0}={1}", key, server == null ? qs[key] : server.UrlEncode(qs[key]));
            }
            return(sb.ToString().TrimStart('&'));
        }
Esempio n. 17
0
    public void Url(string value, HttpServerUtility util, HttpContext ctx)
    {
        // BAD
        var encodedValue = HttpUtility.HtmlEncode(value);

        ctx.Response.Redirect(encodedValue);

        // GOOD
        ctx.Response.Redirect(HttpUtility.UrlEncode(encodedValue));
        ctx.Response.Redirect(util.UrlEncode(encodedValue));
        ctx.Response.Redirect(WebUtility.UrlEncode(encodedValue));
    }
Esempio n. 18
0
        public static void OutputExcel(string fileallpath, HttpServerUtility server, HttpResponse response)
        {
            //string path = server.MapPath(filename + ".xls");

            FileInfo file = new FileInfo(fileallpath);

            response.Clear();
            response.Charset         = "GB2312";
            response.ContentEncoding = Encoding.UTF8;
            response.AddHeader("Content-Disposition", "attachment; filename=" + server.UrlEncode(file.Name));
            response.AddHeader("Content-Length", file.Length.ToString());
            response.ContentType = "application/ms-excel";
            response.WriteFile(file.FullName);
            response.End();
        }
Esempio n. 19
0
        public static void OutputExcelByTemplocation(HttpServerUtility server, HttpResponse response, Application excelapp, _Workbook xBk, _Worksheet xSt, string fileName)
        {
            string tempdirectory = ConfigurationManager.AppSettings["EmployeeExportLocation"];

            if (!Directory.Exists(tempdirectory))
            {
                Directory.CreateDirectory(tempdirectory);
            }
            string templocation = tempdirectory + "\\" + fileName;

            try
            {
                object nothing    = Type.Missing;
                object fileFormat = XlFileFormat.xlExcel8;
                object file       = templocation;
                if (File.Exists(file.ToString()))
                {
                    File.Delete(file.ToString());
                }
                xBk.SaveAs(file, fileFormat, nothing, nothing, nothing, nothing, XlSaveAsAccessMode.xlNoChange, nothing,
                           nothing, nothing, nothing, nothing);
            }
            finally
            {
                xBk.Close(false, null, null);
                excelapp.Quit();
                Marshal.ReleaseComObject(xBk);
                Marshal.ReleaseComObject(excelapp);
                Marshal.ReleaseComObject(xSt);
                GC.Collect();
            }
            FileInfo fileInfo = new FileInfo(templocation);

            if (fileInfo.Exists)
            {
                response.Clear();
                response.Charset         = "GB2312";
                response.ContentEncoding = Encoding.UTF8;
                response.AddHeader("Content-Disposition",
                                   "attachment; filename=" + server.UrlEncode(fileInfo.Name));
                response.AddHeader("Content-Length", fileInfo.Length.ToString());
                response.ContentType = "application/ms-excel";
                response.WriteFile(fileInfo.FullName);
                response.End();
            }
        }
        public NameValueCollection ConfirmPayment(string token, string paymentType, string currencyCodeType, string payerID, string FinalPaymentAmt, List <PayPalItem> items, string customField, string serverName, string itemCategory)
        {
            HttpServerUtility   server = HttpContext.Current.Server;
            NameValueCollection nvpstr = new NameValueCollection();

            nvpstr["TOKEN"]   = server.UrlEncode(token);
            nvpstr["PAYERID"] = server.UrlEncode(payerID);
            nvpstr["PAYMENTREQUEST_0_AMT"]           = server.UrlEncode(FinalPaymentAmt);
            nvpstr["PAYMENTREQUEST_0_PAYMENTACTION"] = server.UrlEncode(paymentType);
            nvpstr["PAYMENTREQUEST_0_CURRENCYCODE"]  = server.UrlEncode(currencyCodeType);
            nvpstr["IPADDRESS"] = server.UrlEncode(serverName);
            nvpstr["PAYMENTREQUEST_0_CUSTOM"] = customField;
            for (int i = 0; i < items.Count; i++)
            {
                nvpstr["L_PAYMENTREQUEST_0_NAME" + i.ToString()]         = items[i].name;
                nvpstr["L_PAYMENTREQUEST_0_AMT" + i.ToString()]          = server.UrlEncode(items[i].amt);
                nvpstr["L_PAYMENTREQUEST_0_QTY" + i.ToString()]          = server.UrlEncode(items[i].qty);
                nvpstr["L_PAYMENTREQUEST_0_ITEMCATEGORY" + i.ToString()] = itemCategory;
            }

            return(hashCall("DoExpressCheckoutPayment", nvpstr));
        }
Esempio n. 21
0
        /// <summary>
        /// Initializes the controls.
        /// </summary>
        /// <param name="container"></param>
        /// <remarks>
        /// Initialize your controls in this method. Do not override CreateChildControls method.
        /// </remarks>
        protected override void InitializeControls(GenericContainer container)
        {
            var sb = new StringBuilder();

            // append fb script
            if (WidgetMode == WidgetModeType.FBML)
            {
                sb.Append(Constants.FBML_SCRIPT);
            }

            // bind html to control
            if (WidgetMode == WidgetModeType.IFRAME)
            {
                sb.AppendFormat(IFRAME_SRC, Server.UrlEncode(this.Url), this.Layout, this.ShowFaces, WidgetWidth, this.Action.ToString().ToLower(), Server.UrlEncode(this.Font.ToLower()), this.ColorScheme.ToString().ToLower(), WidgetHeight);
            }
            else
            {
                sb.AppendFormat(FBML_SRC, HttpContext.Current.Server.UrlEncode(this.Url), this.Layout, this.ShowFaces, WidgetWidth, this.Action.ToString().ToLower(), this.Font.ToLower(), this.ColorScheme.ToString().ToLower());
            }
            LikeButtonHtml.Text = sb.ToString();
        }
Esempio n. 22
0
/*====================================================*/

        public static String AddQuerystringParameter(String aURL, String aParameter, String aValue,
                                                     HttpServerUtility aServer)
        {
            String aNewURL;

            aNewURL = RemoveQuerystringParameter(aURL, aParameter);

            if (aServer != null)
            {
                aValue = aServer.UrlEncode(aValue);
            }

            if (aNewURL.IndexOf("?") != -1)
            {
                aNewURL = aNewURL + "&" + aParameter + "=" + aValue.ToString();
            }
            else
            {
                aNewURL = aNewURL + "?" + aParameter + "=" + aValue.ToString();
            }
            return(aNewURL);
        }
        public NameValueCollection hashCall(String methodName, NameValueCollection nvpStr)
        {
            HttpServerUtility server    = HttpContext.Current.Server;
            WebClient         webClient = new WebClient();

            nvpStr["METHOD"]       = server.UrlEncode(methodName);
            nvpStr["VERSION"]      = server.UrlEncode(version);
            nvpStr["PWD"]          = server.UrlEncode(API_Password);
            nvpStr["USER"]         = server.UrlEncode(API_UserName);
            nvpStr["SIGNATURE"]    = server.UrlEncode(API_Signature);
            nvpStr["BUTTONSOURCE"] = server.UrlEncode(sBNCode);

            var    response = webClient.UploadValues(API_Endpoint, "POST", nvpStr);
            string result   = System.Text.Encoding.UTF8.GetString(response);

            return(deformatNVP(result));
        }
Esempio n. 24
0
    protected void btnSendCode_Click(object sender, EventArgs e)
    {
        if (!usuarioid.HasValue)
        {
            return;
        }

        MembershipUser Usuario = Membership.GetUser(usuarioid, false);

        if (Usuario != null)
        {
            string validationCode = new Random().Next().ToString();

            //1.-Destino del mensaje
            System.Net.Mail.MailAddressCollection MisDestinos = new System.Net.Mail.MailAddressCollection();
            MisDestinos.Add(new System.Net.Mail.MailAddress(Usuario.Email));

            //2.-Cuerpo del mensaje
            HttpServerUtility server   = HttpContext.Current.Server;
            string            sMensaje = "We have sucessfully received your registration request to DropKeys. To complete the subscription process, please click the following link :\r\n\r\n " + Request.Url.GetLeftPart(UriPartial.Authority) + "/validatecode.aspx?email=" +
                                         server.UrlEncode(Usuario.Email) + "&vc=" + validationCode + "\r\n\r\nThank you.";

            if (EmailUtils.SendMessageEmail(MisDestinos, "Verify your email", sMensaje))
            {
                using (Clases.cASPNET_INFO_USUARIO objUsuario = new Clases.cASPNET_INFO_USUARIO())
                {
                    objUsuario.userid = usuarioid;
                    if (objUsuario.bConsultar())
                    {
                        objUsuario.mensaje_validacion = true;
                        objUsuario.validado           = false;
                        objUsuario.codigo_validacion  = validationCode;
                        objUsuario.bModificar();
                    }
                }
            }
        }
    }
Esempio n. 25
0
        public void ExceptionHandlerStarter()
        {
            string            s      = HttpContext.Current.Request.Url.ToString();
            HttpServerUtility server = HttpContext.Current.Server;

            if (server.GetLastError() != null)
            {
                Exception lastError = server.GetLastError();
                Application["LastError"] = lastError;
                int    statusCode        = HttpContext.Current.Response.StatusCode;
                string exceptionOperator = System.Configuration.ConfigurationManager.AppSettings["ExceptionUrl"];
                try
                {
                    exceptionOperator = new System.Web.UI.Control().ResolveUrl(exceptionOperator);
                    if (!String.IsNullOrEmpty(exceptionOperator) && !s.Contains(exceptionOperator))
                    {
                        string url    = string.Format("{0}?ErrorUrl={1}", exceptionOperator, server.UrlEncode(s));
                        string script = String.Format("<script language='javascript' type='text/javascript'>window.top.location='{0}';</script>", url);
                        Response.Write(script);
                        Response.End();
                    }
                }
                catch (Exception)
                {
                }
            }
        }
Esempio n. 26
0
 public string UrlEncode(string s)
 {
     return(_server.UrlEncode(s));
 }
 public override string UrlEncode(string s)
 {
     return(_httpServerUtility.UrlEncode(s));
 }
Esempio n. 28
0
 /// <summary>
 /// URL encodes a string and returns the encoded string.
 /// </summary>
 /// <param name="content">The text to URL encode.</param>
 /// <returns>The URL encoded text.</returns>
 public String UrlEncode(String content)
 {
     return(server.UrlEncode(content));
 }
Esempio n. 29
0
        public List <FileFolderInfo> GetDirectories(string p_folderPath)
        {
            HttpServerUtility     server         = HttpContext.Current.Server;
            string                sortExpression = HttpContext.Current.Request.QueryString["order"];
            List <FileFolderInfo> list           = new List <FileFolderInfo>();
            DirectoryInfo         info3          = new DirectoryInfo(p_folderPath);

            try
            {
                foreach (FileSystemInfo info4 in info3.GetFileSystemInfos())
                {
                    string str2;
                    if (string.IsNullOrEmpty(this._FolderPath))
                    {
                        this._FolderPath = HttpContext.Current.Request.PhysicalApplicationPath + "Files";
                    }

                    if (info4 is DirectoryInfo)
                    {
                        DirectoryInfo info = info4 as DirectoryInfo;
                        if (Utils.Isie())
                        {
                            str2 = "<a href=\"" + Utils.getUrl("filemanager.aspx?path=" + server.UrlEncode(info.FullName) + "") + "\"><img src=\"/Files/sys/IcoFolder.gif\" alt=\"文件夹\" /> " + info.Name + "</a>";
                        }
                        else
                        {
                            str2 = "<a href=\"" + Utils.getUrl("filemanager.aspx?path=" + server.UrlEncode(info.FullName) + "") + "\"> " + info.Name + "</a>";
                        }

                        string compic = "";
                        if (Utils.Isie())
                        {
                            compic = "<img src=\"/Files/sys/IcoPackage.gif\" alt=\"压缩\" />";
                        }
                        else
                        {
                            compic = "[压缩]";
                        }

                        str2 += " <a href=\"" + Utils.getUrl("filemanager.aspx?act=compress&amp;path=" + server.UrlEncode(this._FolderPath) + "&amp;objfolder=" + server.UrlEncode(info.FullName) + "") + "\">" + compic + "</a>";

                        FileFolderInfo info5 = new FileFolderInfo();
                        info5.Name       = info.Name;
                        info5.FullName   = server.UrlEncode(info.FullName);
                        info5.FormatName = str2;
                        info5.Ext        = "";
                        info5.Size       = "0";
                        info5.Type       = "folder";
                        info5.ModifyDate = info.LastWriteTime;
                        list.Add(info5);
                        this._FolderNum++;
                    }
                    else
                    {
                        FileInfo info2 = info4 as FileInfo;
                        // str2 = "<a href=\"file.axd?file=" + server.UrlEncode(info2.FullName) + "\" target=\"_new\"><img src=\"/Files/sys/IcoOtherFile.gif\" alt=\"文件\" /> " + info2.Name + "</a>";
                        if (Utils.Isie())
                        {
                            str2 = "<img src=\"/Files/sys/IcoOtherFile.gif\" alt=\"文件\"/>" + info2.Name + "";
                        }
                        else
                        {
                            str2 = "" + info2.Name + "";
                        }

                        if (info2.Extension.ToLower() == ".zip")
                        {
                            string str3 = str2;
                            if (Utils.Isie())
                            {
                                str2 = str3 + "<a href=\"" + Utils.getUrl("filemanager.aspx?act=unpack&amp;path=" + server.UrlEncode(this._FolderPath) + "&amp;objfile=" + server.UrlEncode(info2.FullName) + "") + "\"><img src=\"/Files/sys/IcoZip.gif\" alt=\"解压\" /></a>";
                            }
                            else
                            {
                                str2 = str3 + "<a href=\"" + Utils.getUrl("filemanager.aspx?act=unpack&amp;path=" + server.UrlEncode(this._FolderPath) + "&amp;objfile=" + server.UrlEncode(info2.FullName) + "") + "\">[解压]</a>";
                            }
                        }
                        else if ((info2.Length < 0xc350L) && this.CheckExtHighlighter(info2.Extension.ToLower()))
                        {
                            if (Utils.Isie())
                            {
                                str2 = str2 + "<a href=\"" + Utils.getUrl("filemanager.aspx?info=text&amp;path=" + server.UrlEncode(this._FolderPath) + "&amp;objfile=" + server.UrlEncode(info2.FullName) + "") + "\"><img src=\"/Files/sys/IcoNotepad.gif\" alt=\"编辑\" /></a>";
                            }
                            else
                            {
                                str2 = str2 + "<a href=\"" + Utils.getUrl("filemanager.aspx?info=text&amp;path=" + server.UrlEncode(this._FolderPath) + "&amp;objfile=" + server.UrlEncode(info2.FullName) + "") + "\">[编辑]</a>";
                            }

                            // if (this.CheckExtHighlighter(info2.Extension.ToLower()))
                            //{
                            ////取虚拟路径
                            //string rootPath = server.MapPath("/");
                            //string FullName = info2.FullName.Remove(0, rootPath.Length);
                            //if (Utils.Isie())
                            //    str2 = str2 + "<a href=\"/" + FullName + "\"><img src=\"/Files/sys/IcoHighlighter.gif\" alt=\"访问\" /></a>";
                            //else
                            //    str2 = str2 + "<a href=\"/" + FullName + "\">[访问]</a>";

                            //}
                        }

                        //取虚拟路径
                        string rootPath = server.MapPath("/");
                        string FullName = info2.FullName.Remove(0, rootPath.Length);
                        if (Utils.Isie())
                        {
                            str2 = str2 + "<a href=\"/" + FullName + "\"><img src=\"/Files/sys/IcoHighlighter.gif\" alt=\"访问\" /></a>";
                        }
                        else
                        {
                            str2 = str2 + "<a href=\"/" + FullName + "\">[访问]</a>";
                        }

                        FileFolderInfo info6 = new FileFolderInfo();
                        info6.Name       = info2.Name;
                        info6.FullName   = server.UrlEncode(info2.FullName);
                        info6.FormatName = str2;
                        info6.Ext        = info2.Extension;
                        info6.Size       = info2.Length.ToString();
                        info6.Type       = "file";
                        info6.ModifyDate = info2.LastWriteTime;
                        list.Add(info6);
                        this._FileNum++;
                    }
                }
                this._Access = true;
            }
            catch
            {
                this._Access = false;
                return(list);
            }
            if (!string.IsNullOrEmpty(sortExpression))
            {
                list.Sort(new FilesComparer(sortExpression));
            }
            return(list);
        }
Esempio n. 30
0
        internal override void RewriteUrl(object sender, EventArgs e)
        {
            var app = (HttpApplication)sender;
            HttpServerUtility server        = app.Server;
            HttpRequest       request       = app.Request;
            HttpResponse      response      = app.Response;
            HttpContext       context       = app.Context;
            string            requestedPath = app.Request.Url.AbsoluteUri;

            if (RewriterUtils.OmitFromRewriteProcessing(request.Url.LocalPath))
            {
                return;
            }

            // 'Carry out first time initialization tasks
            Initialize.Init(app);
            if (!Initialize.ProcessHttpModule(request, false, false))
            {
                return;
            }

            // URL validation
            // check for ".." escape characters commonly used by hackers to traverse the folder tree on the server
            // the application should always use the exact relative location of the resource it is requesting
            var strURL             = request.Url.AbsolutePath;
            var strDoubleDecodeURL = server.UrlDecode(server.UrlDecode(request.RawUrl)) ?? string.Empty;

            if (Globals.FileEscapingRegex.Match(strURL).Success || Globals.FileEscapingRegex.Match(strDoubleDecodeURL).Success)
            {
                DotNetNuke.Services.Exceptions.Exceptions.ProcessHttpException(request);
            }

            try
            {
                // fix for ASP.NET canonicalization issues http://support.microsoft.com/?kbid=887459
                if (request.Path.IndexOf("\\", StringComparison.Ordinal) >= 0 || Path.GetFullPath(request.PhysicalPath) != request.PhysicalPath)
                {
                    DotNetNuke.Services.Exceptions.Exceptions.ProcessHttpException(request);
                }
            }
            catch (Exception exc)
            {
                // DNN 5479
                // request.physicalPath throws an exception when the path of the request exceeds 248 chars.
                // example to test: http://localhost/dotnetnuke_2/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/default.aspx
                Logger.Error(exc);
            }

            string domainName;

            this.RewriteUrl(app, out domainName);

            // blank DomainName indicates RewriteUrl couldn't locate a current portal
            // reprocess url for portal alias if auto add is an option
            if (domainName == string.Empty && CanAutoAddPortalAlias())
            {
                domainName = Globals.GetDomainName(app.Request, true);
            }

            // from this point on we are dealing with a "standard" querystring ( ie. http://www.domain.com/default.aspx?tabid=## )
            // if the portal/url was succesfully identified
            int             tabId           = Null.NullInteger;
            int             portalId        = Null.NullInteger;
            string          portalAlias     = null;
            PortalAliasInfo portalAliasInfo = null;
            bool            parsingError    = false;

            // get TabId from querystring ( this is mandatory for maintaining portal context for child portals )
            if (!string.IsNullOrEmpty(request.QueryString["tabid"]))
            {
                if (!int.TryParse(request.QueryString["tabid"], out tabId))
                {
                    tabId        = Null.NullInteger;
                    parsingError = true;
                }
            }

            // get PortalId from querystring ( this is used for host menu options as well as child portal navigation )
            if (!string.IsNullOrEmpty(request.QueryString["portalid"]))
            {
                if (!int.TryParse(request.QueryString["portalid"], out portalId))
                {
                    portalId     = Null.NullInteger;
                    parsingError = true;
                }
            }

            if (parsingError)
            {
                // The tabId or PortalId are incorrectly formatted (potential DOS)
                DotNetNuke.Services.Exceptions.Exceptions.ProcessHttpException(request);
            }

            try
            {
                // alias parameter can be used to switch portals
                if (request.QueryString["alias"] != null)
                {
                    // check if the alias is valid
                    string childAlias = request.QueryString["alias"];
                    if (!Globals.UsePortNumber())
                    {
                        childAlias = childAlias.Replace(":" + request.Url.Port, string.Empty);
                    }

                    if (PortalAliasController.Instance.GetPortalAlias(childAlias) != null)
                    {
                        // check if the domain name contains the alias
                        if (childAlias.IndexOf(domainName, StringComparison.OrdinalIgnoreCase) == -1)
                        {
                            // redirect to the url defined in the alias
                            response.Redirect(Globals.GetPortalDomainName(childAlias, request, true), true);
                        }
                        else // the alias is the same as the current domain
                        {
                            portalAlias = childAlias;
                        }
                    }
                }

                // PortalId identifies a portal when set
                if (portalAlias == null)
                {
                    if (portalId != Null.NullInteger)
                    {
                        portalAlias = PortalAliasController.GetPortalAliasByPortal(portalId, domainName);
                    }
                }

                // TabId uniquely identifies a Portal
                if (portalAlias == null)
                {
                    if (tabId != Null.NullInteger)
                    {
                        // get the alias from the tabid, but only if it is for a tab in that domain
                        portalAlias = PortalAliasController.GetPortalAliasByTab(tabId, domainName);
                        if (string.IsNullOrEmpty(portalAlias))
                        {
                            // if the TabId is not for the correct domain
                            // see if the correct domain can be found and redirect it
                            portalAliasInfo = PortalAliasController.Instance.GetPortalAlias(domainName);
                            if (portalAliasInfo != null && !request.Url.LocalPath.ToLowerInvariant().EndsWith("/linkclick.aspx"))
                            {
                                if (app.Request.Url.AbsoluteUri.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    strURL = "https://" + portalAliasInfo.HTTPAlias.Replace("*.", string.Empty);
                                }
                                else
                                {
                                    strURL = "http://" + portalAliasInfo.HTTPAlias.Replace("*.", string.Empty);
                                }

                                if (strURL.IndexOf(domainName, StringComparison.InvariantCultureIgnoreCase) == -1)
                                {
                                    strURL += app.Request.Url.PathAndQuery;
                                }

                                response.Redirect(strURL, true);
                            }
                        }
                    }
                }

                // else use the domain name
                if (string.IsNullOrEmpty(portalAlias))
                {
                    portalAlias = domainName;
                }

                // using the DomainName above will find that alias that is the domainname portion of the Url
                // ie. dotnetnuke.com will be found even if zzz.dotnetnuke.com was entered on the Url
                portalAliasInfo = PortalAliasController.Instance.GetPortalAlias(portalAlias);
                if (portalAliasInfo != null)
                {
                    portalId = portalAliasInfo.PortalID;
                }

                // if the portalid is not known
                if (portalId == Null.NullInteger)
                {
                    bool autoAddPortalAlias = CanAutoAddPortalAlias();

                    if (!autoAddPortalAlias && !request.Url.LocalPath.EndsWith(Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase))
                    {
                        // allows requests for aspx pages in custom folder locations to be processed
                        return;
                    }

                    if (autoAddPortalAlias)
                    {
                        AutoAddAlias(context);
                    }
                }
            }
            catch (ThreadAbortException exc)
            {
                // Do nothing if Thread is being aborted - there are two response.redirect calls in the Try block
                Logger.Debug(exc);
            }
            catch (Exception ex)
            {
                // 500 Error - Redirect to ErrorPage
                Logger.Error(ex);

                strURL = "~/ErrorPage.aspx?status=500&error=" + server.UrlEncode(ex.Message);
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Server.Transfer(strURL);
            }

            if (portalId != -1)
            {
                // load the PortalSettings into current context
                var portalSettings = new PortalSettings(tabId, portalAliasInfo);
                app.Context.Items.Add("PortalSettings", portalSettings);

                // load PortalSettings and HostSettings dictionaries into current context
                // specifically for use in DotNetNuke.Web.Client, which can't reference DotNetNuke.dll to get settings the normal way
                app.Context.Items.Add("PortalSettingsDictionary", PortalController.Instance.GetPortalSettings(portalId));
                app.Context.Items.Add("HostSettingsDictionary", HostController.Instance.GetSettingsDictionary());

                if (portalSettings.PortalAliasMappingMode == PortalSettings.PortalAliasMapping.Redirect &&
                    portalAliasInfo != null && !portalAliasInfo.IsPrimary &&
                    !string.IsNullOrWhiteSpace(portalSettings.DefaultPortalAlias))    // don't redirect if no primary alias is defined
                {
                    // Permanently Redirect
                    response.StatusCode = 301;

                    var redirectAlias = Globals.AddHTTP(portalSettings.DefaultPortalAlias);
                    var checkAlias    = Globals.AddHTTP(portalAliasInfo.HTTPAlias);
                    var redirectUrl   = string.Concat(redirectAlias, request.RawUrl);
                    if (redirectUrl.StartsWith(checkAlias, StringComparison.InvariantCultureIgnoreCase))
                    {
                        redirectUrl = string.Concat(redirectAlias, redirectUrl.Substring(checkAlias.Length));
                    }

                    response.AppendHeader("Location", redirectUrl);
                }

                // manage page URL redirects - that reach here because they bypass the built-in navigation
                // ie Spiders, saved favorites, hand-crafted urls etc
                if (!string.IsNullOrEmpty(portalSettings.ActiveTab.Url) && request.QueryString["ctl"] == null &&
                    request.QueryString["fileticket"] == null)
                {
                    // Target Url
                    string redirectUrl = portalSettings.ActiveTab.FullUrl;
                    if (portalSettings.ActiveTab.PermanentRedirect)
                    {
                        // Permanently Redirect
                        response.StatusCode = 301;
                        response.AppendHeader("Location", redirectUrl);
                    }
                    else
                    {
                        // Normal Redirect
                        response.Redirect(redirectUrl, true);
                    }
                }

                // manage secure connections
                if (request.Url.AbsolutePath.EndsWith(".aspx", StringComparison.InvariantCultureIgnoreCase))
                {
                    // request is for a standard page
                    strURL = string.Empty;

                    // if SSL is enabled
                    if (portalSettings.SSLEnabled)
                    {
                        // if page is secure and connection is not secure orelse ssloffload is enabled and server value exists
                        if ((portalSettings.ActiveTab.IsSecure && !request.IsSecureConnection) &&
                            (UrlUtils.IsSslOffloadEnabled(request) == false))
                        {
                            // switch to secure connection
                            strURL = requestedPath.Replace("http://", "https://");
                            strURL = this.FormatDomain(strURL, portalSettings.STDURL, portalSettings.SSLURL);
                        }
                    }

                    // if SSL is enforced
                    if (portalSettings.SSLEnforced)
                    {
                        // if page is not secure and connection is secure
                        if (!portalSettings.ActiveTab.IsSecure && request.IsSecureConnection)
                        {
                            // check if connection has already been forced to secure orelse ssloffload is disabled
                            if (request.QueryString["ssl"] == null)
                            {
                                strURL = requestedPath.Replace("https://", "http://");
                                strURL = this.FormatDomain(strURL, portalSettings.SSLURL, portalSettings.STDURL);
                            }
                        }
                    }

                    // if a protocol switch is necessary
                    if (!string.IsNullOrEmpty(strURL))
                    {
                        if (strURL.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase))
                        {
                            // redirect to secure connection
                            response.RedirectPermanent(strURL);
                        }
                        else

                        // when switching to an unsecure page, use a clientside redirector to avoid the browser security warning
                        {
                            response.Clear();

                            // add a refresh header to the response
                            response.AddHeader("Refresh", "0;URL=" + strURL);

                            // add the clientside javascript redirection script
                            response.Write("<html><head><title></title>");
                            response.Write("<!-- <script language=\"javascript\">window.location.replace(\"" + strURL +
                                           "\")</script> -->");
                            response.Write("</head><body></body></html>");

                            // send the response
                            response.End();
                        }
                    }
                }
            }
            else
            {
                // alias does not exist in database
                // and all attempts to find another have failed
                // this should only happen if the HostPortal does not have any aliases
                // 404 Error - Redirect to ErrorPage
                strURL = "~/ErrorPage.aspx?status=404&error=" + domainName;
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Server.Transfer(strURL);
            }

            if (app.Context.Items["FirstRequest"] != null)
            {
                app.Context.Items.Remove("FirstRequest");

                // Process any messages in the EventQueue for the Application_Start_FirstRequest event
                EventQueueController.ProcessMessages("Application_Start_FirstRequest");
            }
        }