Friday, 12 September 2014

Html file call in Master page as contain placeholder -- dynamic usercontrol for all pages as per folder /page

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;

public partial class Html_htmlcall : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            try
            {
                //------------------------find file name with folder name start code-------------

                string filename = Path.GetFileName(HttpContext.Current.Request.Url.AbsolutePath);
                string urlname = HttpContext.Current.Request.Url.AbsolutePath;
                //for my local
               //urlname = urlname.Replace("/NewRnd", "");
                //compete
                string folderpath = urlname.Replace("/" + filename, "");
                if (folderpath.StartsWith("/"))
                {
                    folderpath = folderpath.Remove(0, 1);
                }
                string[] folderlength = folderpath.Split('/');
                string newfolderpath = "";
                if (folderlength.Length > 0)
                {
                    foreach (string s in folderlength)
                    {
                        newfolderpath = newfolderpath + s + "-";
                    }
                }
                if (newfolderpath.Length == 1)
                {
                    newfolderpath = "";
                }

                //---------------------------end code-------------

                //Response.Write(newfolderpath);

                string uriFileExt = Path.GetExtension(HttpContext.Current.Request.Url.AbsolutePath);// HttpContext.Current.Request.Url.AbsoluteUri;
                string uri1 = HttpContext.Current.Request.Url.AbsoluteUri.Replace(uriFileExt, ".html");
                string pagename=Path.GetFileName(HttpContext.Current.Request.Url.AbsolutePath).Replace(uriFileExt, ".html");
                //string uri = "http://10.132.150.2:8313/thankyou.html";
                string uri = "http://" + HttpUtility.UrlDecode(HttpContext.Current.Request.ServerVariables["http_host"] + "/uploads/"+ newfolderpath+ pagename);

               // string uri = "http://" + HttpUtility.UrlDecode(HttpContext.Current.Request.ServerVariables["http_host"] + "/uploads/voting-policy.html");
                HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
                req.KeepAlive = false;
                //req.ContentLength = 0;
                //req.ContentType = "text/json";
                //Stream data = req.GetRequestStream();
                //data.Close();
                string result;
                using (WebResponse resp = req.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
                    {
                        result = reader.ReadToEnd();
                    }
                }
                htmlprindiv.InnerHtml = result;
                // rtxtResult.AppendText(htmlText);
            }
            catch (Exception ex)
            {
                //rtxtResult.AppendText(ex.Message);
            }
        }
    }
}

Monday, 25 August 2014

Server Variable for page url

string url = HttpContext.Current.Request.Url.AbsoluteUri;
// http://localhost:1302/TESTERS/Default6.aspx

string path = HttpContext.Current.Request.Url.AbsolutePath;
// /TESTERS/Default6.aspx

string host = HttpContext.Current.Request.Url.Host;
// localhost
Path.GetFileName( Request.Url.AbsolutePath )
pramod.aspx
EXAMPLE (Sample URL)
http://localhost:60527/WebSite1test/Default2.aspx?QueryString1=1&QuerrString2=2
HttpContext.Current.Request.Url.Host
HttpContext.Current.Request.Url.Authority
HttpContext.Current.Request.Url.AbsolutePath
HttpContext.Current.Request.ApplicationPath
HttpContext.Current.Request.Url.AbsoluteUri
HttpContext.Current.Request.Url.PathAndQuery
localhost
localhost:60527
/WebSite1test/Default2.aspx
/WebSite1test
http://localhost:60527/WebSite1test/Default2.aspx?QueryString1=1&QuerrString2=2
/WebSite1test/Default2.aspx?QueryString1=1&QuerrString2=2
EXAMPLE (Sample URL)
http://localhost:60527/WebSite1test/Default2.aspx?QueryString1=1&QuerrString2=2
string url = Request.Url.Host;
localhost:2806 
"http://localhost:1234/Default.aspx?un=asdf&somethingelse=fdsa"
or like this:
"https://www.something.com/index.html?a=123&b=4567"
and you only want the part that a user would type in then this will work:
String strPathAndQuery = HttpContext.Current.Request.Url.PathAndQuery;
String strUrl = HttpContext.Current.Request.Url.AbsoluteUri.Replace(strPathAndQuery, "/");
which would result in these:
"http://localhost:1234/"
"https://www.something.com/"

Tuesday, 19 August 2014

Download file on html page use handler file

html code

    <a  id="downloadfile" href='pdfHandlerfile.ashx?filename=file1.pdf' target="_self" >download</a>
---------------------------------------------------------
<%@ WebHandler Language="C#" Class="pdf_Handler" %>

using System;
using System.Web;
using System.IO;
 
public class pdfHandlerfile : IHttpHandler {
   
    public void ProcessRequest (HttpContext context) {
     
    if( HttpContext.Current.Request.QueryString["filename"] !=null)
        PDFdownload(HttpContext.Current.Request.QueryString["filename"].ToString());
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

    public void PDFdownload(string filename)
    {
        try
        {

            string contentType = "Application/pdf";
            HttpContext.Current.Response.ContentType = contentType;
            HttpContext.Current.Response.AppendHeader("content-disposition", "attachment; filename="+filename+"");

            //Write the file directly to the HTTP content output stream.
            HttpContext.Current.Response.WriteFile(HttpContext.Current.Server.MapPath(filename));
            HttpContext.Current.Response.End();
        }
        catch (Exception ex)
        {
        }
    }

}

Tuesday, 12 August 2014

json, jquery, JavaScript search as per first character and string autocomplete.


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script type="text/javascript" src="../js1/jquery-1.7.1.min.js"></script>
<script  type="text/javascript" src="../js1/jquery.ui.core.min.js"></script>
<script  type="text/javascript" src="../js1/jquery.ui.widget.min.js"></script>
<script  type="text/javascript" src="../js1/jquery.ui.position.min.js"></script>
<script  type="text/javascript" src="../js1/jquery.ui.autocomplete.min.js"></script>
    <script type="text/javascript">
        var availableTags;
        var re = "";
          var res ="";
          var res1 = "";
          var r = 0;
     
         function setval1( kk)
         {
             $("#txtHour").val(kk);
         }
           $(function () {
               var cValue = document.getElementById("hdnList").value
               var list = cValue.split(",");
               availableTags = list;
               $("#txtHour").autocomplete({
                   autoFocus: true,
                   source: availableTags,
                   multiple: true,
                   matchContains: true,
                   open: function (event, ui) {
                       //alert("hej" + availableTags);
                   }
               })
               .data("autocomplete")._renderItem = function (ul, item) {
                   res1 = item.value;
                   res = $("#txtHour").val();
                   r1 = res.length;
                   res1 = res1.substring(0, parseInt(r1));
                   res = res.substring(0, parseInt(r1));
                   if (res1 == res) {
                       return $("<li></li>").data("item.autocomplete", item)
                    .append("<a>" + item.value +  "</a>")
                    .appendTo(ul);
                       
                   }
                   return false;
               };
           });
    </script>

     <script language="javascript" type="text/javascript">
         function validateCheckBoxes(source, args) {
             var cValue = document.getElementById("hdnList").value
             var list = cValue.split(",");
             availableTags = list;
             var flag = false;
             for (var i = 0; i < list.length; i++) {
                 if (list[i].toString() == document.getElementById("txtHour").value.toString()) {
                     flag = true;
                 }
             }
             if (flag)
                 args.IsValid = true;
             else
                 args.IsValid = false;
               
         }
    </script>
</head>
<body>
    <form id="form1" runat="server">
 
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
     <asp:HiddenField ID="hdnList" Value="21:AM,2:AM,3:AM,4:AM,5:AM,6:AM,7:AM,8:AM,9:AM,10:AM,11:AM,12:AM,32:AM,22:AM,mumbai,abmumbai,ccmumbai"
        runat="server" />
                  <asp:TextBox ID="txtHour" runat="server" onblur="if (this.value == '') {this.value='Type Hour'}"
                                                            onfocus="if (this.value =='Type Hour') {this.value = ''}" MaxLength="15" Text="Type Hour" ClientIDMode="Static"></asp:TextBox>
<asp:CustomValidator id="CustomValidator1" runat="server" ErrorMessage="Not match City Name"  EnableClientScript="true"
                 ClientValidationFunction="validateCheckBoxes">
                </asp:CustomValidator>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </div>  <div id="search" ></div>
    </form>
</body>
</html>

Tuesday, 15 July 2014

ajax file extention allow and wrong file .axd redirect on error page

<configuration>
<system.web>
    <trace enabled="false"/>
<pages viewStateEncryptionMode="Always" enableViewStateMac="false"></pages>
<compilation debug="true" targetFramework="4.0"/>
<customErrors mode="On" defaultRedirect="~/error.html">
<error statusCode="403" redirect="~/error.html"/>
<error statusCode="404" redirect="~/error.html"/>
<error statusCode="500" redirect="~/error.html"/>
</customErrors>
    <httpRuntime enableVersionHeader="false"/>
    <!--Below Added to secure cookie-->
    <httpCookies httpOnlyCookies="true" requireSSL="false"/>
    <!--Above Added to secure cookie-->
</system.web>
  <system.webServer>
  <!--The following configuration sample adds an HTTP "Cache-Control: no-cache" header to the response, thereby disabling caching of requests.-->
  <staticContent>
    <clientCache cacheControlMode="DisableCache" />
  </staticContent>
  <!--Above Added to HTTP "Cache-Control: no-cache" header to the response, thereby disabling caching of requests.-->
  </system.webServer>
<system.net>
<mailSettings>
<smtp>
<network host="localhost"/>
</smtp>
</mailSettings>
</system.net>
</configuration>

Friday, 11 July 2014

Rs. string format like 10,00,00,000.00 in .net

 int num=100000000;
 string oo = String.Format("{0:## ## ## ###.00}", num).Trim();
 oo = oo.Replace(' ', ',');

Friday, 4 July 2014

Security for page submit

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogic;
using System.Net.Mail;
using System.Text;
using System.Configuration;

public partial class equity_opportunity_series : System.Web.UI.Page
{
    EquityOpportunity_Promo EQpromo = new EquityOpportunity_Promo();
 
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
           
            Session["CheckRefreshA"] = Server.UrlDecode(System.DateTime.Now.ToString());
        }
    }
   #region Page Init
private void Page_Init(object sender, EventArgs e)
    {
        Page.ClientTarget = "uplevel";
    }

   #endregion
 #region Page Pre Render
    protected void Page_PreRender(object sender, EventArgs e)
    {
        ViewState["CheckRefreshA"] = Session["CheckRefreshA"];
    }
    #endregion
 
    protected void imgBtnSubmit_Click(object sender, EventArgs e)
    {
        try
        {

            if (Page.IsValid)
            {
                if (Session["CheckRefreshA"] != null)
                {
                    if (Session["CheckRefreshA"].ToString() == ViewState["CheckRefreshA"].ToString())
                    {
                     
                        Session["CheckRefreshA"] = Server.UrlDecode(System.DateTime.Now.ToString());
                     
                    }
                    else
                    {
                     
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw (ex);
        }
    }
 

 
}