Friday, 28 November 2014

upload excel file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Data.OleDb;
using System.Data;


public partial class Upload_presnews_file : System.Web.UI.Page
{
    string _strKVBDataConnString;

    public string StrKVBDataConnString
    {
        get { return _strKVBDataConnString; }
        set { _strKVBDataConnString = value; }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {

         



          
        }
        catch (Exception ex)
        {
            // lblErrMsg.Text = ex.Message.ToString();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {

        if (Page.IsValid)
        {
            try
            {
                #region variable
                string FULLNAME, ADDRESS, COUNTRY, STATE, DISTRICT, PINCOD, FOLIO_No, INVESTTYPE, NETDIV, Dividend_Year;
                //DateTime IEPFTRDATE, Date_of_Dividend;
               string IEPFTRDATE, Date_of_Dividend;
                ArrayList _event = new ArrayList();
                #endregion

                string strFolderName = Server.MapPath("iepf/");
                string strFolderPath = "";
                FileUploadiepf.SaveAs(strFolderName + FileUploadiepf.FileName);
                string strFileType = System.IO.Path.GetExtension(FileUploadiepf.FileName).ToLower();
                //        StrKVBDataConnString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
                //@"Data Source=" + strFolderPath + ";" +
                //"Extended Properties=\"Text;HDR=Yes;FORMAT=Delimited\"";
                //StrKVBDataConnString = ("Provider=Microsoft.ACE.OLEDB.12.0;" +
                //  "Data Source=" + strFolderName + FileUploadiepf.FileName + ";" +
                //  "Extended Properties=Excel 12.0 Xml");


                if (strFileType.ToLower() == ".xlsx".ToLower())
                {
                    //strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filetoread + ";" + "Extended Properties=Excel 12.0;";   //Previous Code
                    StrKVBDataConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strFolderName + FileUploadiepf.FileName + @";Extended Properties=" + Convert.ToChar(34).ToString() + @"Excel 12.0;Imex=1;HDR=Yes;" + Convert.ToChar(34).ToString(); //Modified Code
                }
                else
                {
                    //strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filetoread + ";" + "Extended Properties=Excel 8.0;"; //Previous Code
                    StrKVBDataConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strFolderName + FileUploadiepf.FileName + @";Extended Properties=" + Convert.ToChar(34).ToString() + @"Excel 8.0;Imex=1;HDR=Yes;" + Convert.ToChar(34).ToString();   //Modified Code
                    //strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filetoread + ";" + "Extended Properties=Excel 8.0;HDR=YES;";
                }

               
                //StrKVBDataConnString = ("Provider=Microsoft.ACE.OLEDB.12.0;" +
                //"Data Source=" + strFolderName + FileUploadiepf.FileName + ";" +
                //"Extended Properties=Excel 8.0 Xml; HDR=YES");
                OleDbConnection objConnection;
                OleDbDataAdapter adapter;
                objConnection = new OleDbConnection(StrKVBDataConnString);
                objConnection.Open();


                //FileUploadiepf.SaveAs( strFolderName+ FileUploadiepf.FileName);

                string strQuery = "SELECT * FROM [Sheet1$]";

                //OleDbConnection objConnection = new OleDbConnection(StrKVBDataConnString);
                //objConnection.Open();
                OleDbDataAdapter EventDataDataAdapter = new OleDbDataAdapter(strQuery, objConnection);

                DataSet EventDataDataSet = new DataSet();
                // Populate the DataSet with the spreadsheet worksheet data
                EventDataDataAdapter.Fill(EventDataDataSet);
                objConnection.Close();

                _event.Add(@"exec sp_stattv_pressnews 'delete'");

                System.Text.StringBuilder EventDataStrB = new System.Text.StringBuilder();

                EventDataStrB.Append("Declare @ID As bigint  ");
                foreach (DataRow drr in EventDataDataSet.Tables[0].Rows)
                {
                    //AMFIcode = drr["AMFIcodenew"].ToString();
                    //eventName = drr["EVENTNAME"].ToString();
                    FULLNAME = drr["FULLNAME"].ToString();
                    ADDRESS = drr["ADDRESS"].ToString();
                    COUNTRY = drr["COUNTRY"].ToString();
                    STATE = drr["STATE"].ToString();
                    DISTRICT = drr["DISTRICT"].ToString();
                    PINCOD = drr["PINCOD"].ToString();
                    FOLIO_No = drr["FOLIO No"].ToString();
                    INVESTTYPE = drr["INVESTTYPE"].ToString();
                    NETDIV = drr["NETDIV"].ToString();
                    try
                    {
                           IEPFTRDATE = Convert.ToDateTime(drr["IEPFTRDATE"]).ToString("yyyy/MM/dd HH:mm:ss");
                    }
                    catch
                    {
                        IEPFTRDATE = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
                    }
                    Dividend_Year = drr["Dividend Year"].ToString();
                    try
                    {     Date_of_Dividend = Convert.ToDateTime(drr["Date of Dividend"]).ToString("yyyy/MM/dd HH:mm:ss");
                        //Date_of_Dividend = txtYear + "/" + txtMonth + "/" + txtDate +" 12:00:00 AM";
                    }
                    catch
                    {
                        Date_of_Dividend = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
                    }
                    //Response.Write(Date_of_Dividend + "<br/>" + IEPFTRDATE);

                    if (!string.IsNullOrEmpty(FOLIO_No))
                    {
                        _event.Add(@"exec sp_stattv_pressnews 'newsDATAInsert','" + FULLNAME + "','" + ADDRESS + "','" + COUNTRY + "','" + STATE + "','"
                            + DISTRICT + "','" + PINCOD + "','" + FOLIO_No + "','" + INVESTTYPE + "','" + NETDIV
                            + "','" + IEPFTRDATE + "','" + Dividend_Year + "','" + Date_of_Dividend + "' ");
                        //Response.Write(@"exec sp_KVB_IEPF 'IEPFDATAInsert','" + FULLNAME + "','" + ADDRESS + "','" + COUNTRY + "','" + STATE + "','"
                        //   + DISTRICT + "','" + PINCOD + "','" + FOLIO_No + "','" + INVESTTYPE + "','" + NETDIV
                        //   + "','" + IEPFTRDATE + "','" + Dividend_Year + "','" + Date_of_Dividend + "' ");
                    }

                }
                SqlHelper _sqlHelper = new SqlHelper();
                bool flag = false;
                try
                {
                     flag = SqlHelper.MultiTransaction(_sqlHelper.Connection, _event);

                }
                catch (Exception ex)
                {
                    Response.Write(ex.ToString());
                }

                if (flag)
                {
                    Response.Write("File Imported Successfully: strFileNameToImport <br/>");
                }
                else
                {
                    Response.Write("Error Occurred While Importing Data: <br/>");
                }




            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }
    }
}

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);
        }
    }
 

 
}

Thursday, 26 June 2014

Download file in zip format


using Ionic.Zip;

protected void btnDownload_Click(object sender, EventArgs e)
    {
        using (ZipFile zip = new ZipFile())
        {
            foreach (GridViewRow gvrow in gvDetails.Rows)
            {
                CheckBox chk = (CheckBox)gvrow.FindControl("chkSelect");
                if (chk.Checked)
                {
                    string fileName = gvrow.Cells[1].Text;
                    string filePath = Server.MapPath("~/UploadedResumeByUsers/" + fileName);
                    zip.AddFile(filePath, "files");
                }
            }
            Response.Clear();
            Response.AddHeader("Content-Disposition", "attachment; filename=DownloadedFile.zip");
            Response.ContentType = "application/zip";
            zip.Save(Response.OutputStream);
            Response.End();
        }
    }    

Thursday, 12 June 2014

Excel Insert, Update, Delete by .net

--------aspx-----------
 <asp:Button ID="create" runat="server" Text="create" /><br />
        <asp:Button ID="insert" runat="server" Text="insert" /><br />
        <asp:Button ID="select1" runat="server" Text="select" /><br />
        <asp:Button ID="update" runat="server" Text="update" /><br />
----------------------cs---------------
Imports System.Data.OleDb
Partial Class excel_update
    Inherits System.Web.UI.Page
    'Private m_sConn1 As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:\ExcelData2.xls;Extended Properties=Excel 8.0"
    'Private m_sConn2 As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:\ExcelData2.xls;Extended Properties=Excel 8.0"
    'Private m_sAction As String

    Protected Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles form1.Load

     
    End Sub
    Private Function CreateConnString(ByVal Str As String) _
        As String

        Return "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" _
        + Str + ";Extended Properties=""Excel 8.0;HDR=YES;"""


    End Function
     ';;;;;;;;;;;;
    Protected Sub create_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles create.Click
        Dim Conn As New OleDbConnection
        Dim Comm As New OleDbCommand

        Conn.ConnectionString = CreateConnString("D:\RND\test\excel\Book1.xls")
        Comm.Connection = Conn
        Comm.CommandText = _
         "Create Table MySheet (F1 char(255), F2 char(255))"

        Try
            Conn.Open()
            Comm.ExecuteNonQuery()
            MsgBox("Created.")
            Conn.Close()
        Catch ex As Exception
            MsgBox("Error.")
            Conn.Close()
        End Try
    End Sub

    Protected Sub insert_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles insert.Click
        Dim Conn As New OleDbConnection
        Dim Comm As New OleDbCommand

        Conn.ConnectionString = CreateConnString("D:\RND\test\excel\Book1.xls")
        Comm.Connection = Conn
        Comm.CommandText = _
         "Insert INTO [MySheet$] (F1, F2) Values ('1','2')"

        Try
            Conn.Open()
            Comm.ExecuteNonQuery()
            MsgBox("Inserted.")
            Conn.Close()
        Catch ex As Exception
            MsgBox("Error.")
            Conn.Close()
        End Try
    End Sub

    Protected Sub select1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles select1.Click
        Dim Conn As New OleDbConnection
        Dim Comm As New OleDbCommand
        Dim DReader As OleDbDataReader
        Dim Str As String = ""

        Conn.ConnectionString = CreateConnString("D:\RND\test\excel\Book1.xls")
        Comm.Connection = Conn
        Comm.CommandText = "Select [F1], [F2] From [MySheet$]"

        Try
            Conn.Open()
            DReader = Comm.ExecuteReader

            Do While DReader.Read
                Str = Str + vbCrLf + DReader.GetString(0) _
                + " , " + DReader.GetString(1)
            Loop

            MsgBox(Str)
            DReader.Close()
            Conn.Close()
        Catch ex As Exception
            MsgBox("Error.")
            Conn.Close()
        End Try

    End Sub

    Protected Sub update_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles update.Click

        Dim Conn As New OleDbConnection
        Dim Comm As New OleDbCommand

        Conn.ConnectionString = CreateConnString("D:\RND\test\excel\Book1.xls")
        Comm.Connection = Conn
        Comm.CommandText = _
         "Update [MySheet$] SET F1 = 'pramod' Where F2 = '2'"

        Try
            Conn.Open()
            Comm.ExecuteNonQuery()
            MsgBox("Updated.")
            Conn.Close()
        Catch ex As Exception
            MsgBox("Error.")
            Conn.Close()
        End Try
    End Sub
End Class

Dictionary use for filter by Alfabet .net

--------------aspx---------------
 <div>
    <asp:Repeater ID="FilteringUI"  runat="server" OnItemCommand="FilteringUI_ItemCommand">
            <ItemTemplate>
                <asp:LinkButton runat="server" ID="lnkFilter" Text='<%# Container.DataItem %>' CommandName='<%# Container.DataItem %>'>
                </asp:LinkButton>
            </ItemTemplate>
            <SeparatorTemplate>
                |</SeparatorTemplate>
        </asp:Repeater>
    </div>
    <asp:GridView ID="gridUsers" runat="server">
        </asp:GridView>
--------------------cs--------------------------------
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class birla_xml_loc_panel_Directory : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        BindFilteringUI();
    }
    private void BindFilteringUI()
    {
        string[] filterOptions = { "All", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
        FilteringUI.DataSource = filterOptions;
        FilteringUI.DataBind();
    }
    protected void FilteringUI_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "All")
            this.UsernameToMatch = string.Empty;
        else
            this.UsernameToMatch = e.CommandName;
        BindUserAccounts();
    }
     private void BindUserAccounts()
    {
       
        if (this.UsernameToMatch == "")
        {SqlConnection con =new SqlConnection ("server=10.0.0.11;database=planetm;uid=sa;pwd=sa;");
            DataSet ds=new DataSet ();
            SqlDataAdapter da=new SqlDataAdapter ("select username,lastname from UserProfile ",con);
            da.Fill (ds);
            gridUsers.DataSource = ds;
            gridUsers.DataBind();
        }
        else
        {
            string str = this.UsernameToMatch;
            SqlConnection con = new SqlConnection("server=10.0.0.11;database=planetm;uid=sa;pwd=sa;");
            DataSet ds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter("select username,lastname from UserProfile where username like '" + str + "%' ", con);
            da.Fill(ds);
            gridUsers.DataSource = ds;
            gridUsers.DataBind();
        }
    }
    private string UsernameToMatch
    {
        get
        {
            object o = ViewState["UsernameToMatch"];
            if (o == null)
                return string.Empty;
            else return (string)o;
        }
        set
        {
            ViewState["UsernameToMatch"] = value;
        }
    }
}

Two Query one No column in VB.net

 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim con As New SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=pramod;Integrated Security=True;")

        Dim ds As New DataSet
        Dim dsa As New DataSet
        Dim dr As New SqlDataAdapter("SELECT count(name)+ 1+ROW_NUMBER()  OVER (ORDER BY name) AS id ,name FROM test1 group by name; SELECT ROW_NUMBER()  OVER (ORDER BY lastname) AS id, lastname FROM test2; ", con)

        dr.Fill(ds)

        Dim i As Integer = 0
        Dim table As DataTable = ds.Tables(0)
        table.Columns.Add(New DataColumn("no", GetType(Integer)))
        Dim rowcount As Integer = table.Rows.Count
        Dim k As Integer = 1
        While (i < rowcount)
            table.Rows(i)("no") = k
            i = i + 1
            k = k + 1

        End While

        GridView1.DataSource = table
        GridView1.DataBind()
        Dim j As Integer = 0
        Dim tablea As DataTable = ds.Tables(1)
        tablea.Columns.Add(New DataColumn("no", GetType(Integer)))
        rowcount = tablea.Rows.Count
        While (j < rowcount)
            tablea.Rows(j)("no") = k
            k = k + 1
            j = j + 1
        End While
        GridView2.DataSource = tablea
        GridView2.DataBind()
       

    End Sub

Monday, 9 June 2014

Create Global Variable in xsl and value assign by c sharp function in xsl all those thing in one xsl

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt"
                xmlns:tns="urn:thisnamespace:tns"  exclude-result-prefixes="tns msxsl"
                >
<xsl:output method="xml" indent="yes" encoding="utf-8" omit-xml-declaration="yes"/>
  <xsl:param name="currentPage"/>
  <xsl:param name="PageUrl" />
  <xsl:param name="url"/>
  <xsl:param name="hanmant"/>
  <xsl:param name="date"  />

  <msxsl:script language="C#"   implements-prefix="tns">
     <msxsl:assembly name="System" />
     <msxsl:using namespace="System" />
     <msxsl:assembly name="System.Web" />
     <msxsl:using namespace="System.Web" />
     <msxsl:assembly name="System.Configuration"/>
     <msxsl:using namespace="System.Configuration"/>
     <msxsl:using namespace="System.Xml"/>
     <msxsl:using namespace="System.Xml.XPath"/>
    <msxsl:assembly name="System.Data"/>
    <msxsl:using namespace="System.Data"/>
  <msxsl:using namespace="System.Data.SqlClient"/>
   <![CDATA[
   
  public string databaseaccess()
    {
         String query, kk= "<table border='1px'><tr><td>Sr no.</td><td>Name</td><td>File Path</td></tr>";
      try
                {
        SqlConnection con = new SqlConnection("Data Source=INMUBLBW0709\\SQLEXPRESS2008;Initial Catalog=idfcmf;Persist Security Info=True;User ID=sa;Password=admin123");
        con.Open();
         int i=0;
        query = "select * from DownloadCenter";
        SqlCommand cmd = new SqlCommand(query, con);
        SqlDataReader dr;
        //cmd.Parameters.Add("@id", SqlDbType.Int).Value = name.Value;
        //cmd.Parameters.Add("@name", SqlDbType.VarChar).Value = address.Value;
        dr = cmd.ExecuteReader();
        dr.Read();
        while (dr.Read())
        {
          i=i+1;
            kk = kk+"<tr><td> "+i+" </td><td>"+ dr["Title"].ToString()+"</td><td>"+ dr["uploadfile"].ToString()+"</td></tr>";
            //Text3.Value = dr(1)
        }
         kk = kk + "</table>";
             }
        catch (Exception ex)
        {
            return ex.ToString();
        }
         return kk;
       

    }
   
 public string readxml()
    {
        string xmlstring = "<table border='1px'><tr><td>Sr no.</td><td>Name</td></tr>";
        int i=0;
        string link1 = HttpContext.Current.Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["NavXML"]);
        try
        {
            XmlDocument xmlDoc = new XmlDocument();
           xmlDoc.Load(link1);
         
            XmlNode titleNode = xmlDoc.SelectSingleNode("site//global");

            foreach (XmlNode xn in titleNode)
            {
                  i=i+1;
                try
                {
                  xmlstring = xmlstring +"<tr><td> "+i+" </td><td>"+ xn.Attributes["caption"].Value +"</td></tr>";//innertext
                }
                catch
                {
                }

            }
            xmlstring = xmlstring + "</table>";

        }
        catch (Exception ex)
        {
            return ex.ToString();
        }

        return xmlstring;
    }
   
    public string LinkFile()
    {
         string link = System.Configuration.ConfigurationManager.AppSettings["SiteURL"];
         return link;
    }
   
    public double calculation(double radius){
       double pi = 3.14;
       double circ = pi*radius*2;
       return circ;
     }
 
   public string circumference()
      {
      DateTime date = DateTime.Now;
        string vv =date.ToString()+HttpContext.Current.Request.Url.AbsoluteUri.ToString().ToLower().Replace("http://"+HttpContext.Current.Request.Url.Authority.ToString(),"");// date.ToString();
         return vv;
      }
      public string mydate()
      {
      DateTime date = DateTime.Now;
        string vv = date.ToString();
         return vv;
      }
]]>
 
  </msxsl:script>
 
<xsl:variable name="cdtitle">
  <xsl:value-of select="tns:readxml()"/>
</xsl:variable>
  <xsl:param name="date1"  >
    <xsl:value-of select="tns:mydate()"/>
  </xsl:param>
<xsl:variable name="smallcase" select="'abcdefghijklmnopqrstuvwxyz'" />
  <xsl:variable name="uppercase" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'" />


  <xsl:template match="/">
    <xsl:text disable-output-escaping="yes">
<![CDATA[
       <script type="text/javascript">
     

        function callme() {
          alert('pramod');
    }
</script>
]]>
</xsl:text>
  <br/><xsl:value-of select="$cdtitle"/><br/>
    <div onclick="callme();">
      <xsl:value-of select="tns:circumference()"/></div>


    after load Request.Url.ToString():=  <input type="button" value="Stampa" onclick="callme();"></input>
 
     <xsl:value-of select="$hanmant"/>  <xsl:value-of select="$currentPage"/>
    <xsl:value-of select="$date1"/>new
    <xsl:apply-templates select="." mode="GetData" />
  </xsl:template>
  <xsl:template match="site" mode="GetData">
 
    <xsl:for-each select="main/page">
      11<xsl:value-of select="current()"/>22
      <ul class="col{position()}">
        <li>
          <span>

            pramod:--
         <xsl:value-of select="$date"/>
            --tests
            <xsl:value-of select="@caption"/>
          </span>
          <span>
           
            <xsl:value-of select="@caption"/>
          </span>
          <xsl:call-template name="drawChildNodes">
            <xsl:with-param name="parentnode" select="."/>
          </xsl:call-template>
        </li>
      </ul>
    </xsl:for-each>
  </xsl:template>

  <xsl:template name="drawChildNodes">
    <xsl:param name="parentnode"></xsl:param>

    <xsl:if test="count($parentnode/page) &gt; 0">
      <ul>
        <xsl:for-each select="$parentnode/page">
       
          <!--<li>
            link:-<xsl:value-of select="$currentPage"/>=<xsl:value-of select="translate(@link, $uppercase , $smallcase)"/>
           
          </li>-->
          <li >
         
            <xsl:if test="$currentPage=translate(@link, $uppercase , $smallcase)">
              <xsl:attribute name="style">color:Red</xsl:attribute>
            </xsl:if>
            <xsl:choose>
              <xsl:when test="@label=1">

                <span>
               
                  <xsl:value-of select="@caption"/>

                </span>
              </xsl:when>
              <xsl:otherwise>
                <a href="#" rel="{@rel}">

                  <!--Added by anup on 10/04/2014-->
                  <xsl:if test="@class!=''">
                    <xsl:attribute name="class">
                      <xsl:value-of select="@class"/>
                    </xsl:attribute>
                  </xsl:if>
                  <!--Added by anup on 10/04/2014-->

                  <xsl:if test="@link!=''">
                    <xsl:attribute name="href">
                      <xsl:value-of select="@link"/>
                    </xsl:attribute>
                  </xsl:if>
                  <xsl:if test="@target!=''">
                    <xsl:attribute name="target">
                      <xsl:value-of select="@target"/>
                    </xsl:attribute>
                  </xsl:if>
                  <xsl:value-of select="@caption"/>
                </a>
              </xsl:otherwise>
            </xsl:choose>
            <xsl:if test="number(@level) &lt;= 2">
              <xsl:call-template name="drawChildNodes">
                <xsl:with-param name="parentnode" select="."/>
              </xsl:call-template>
            </xsl:if>
          </li>
        </xsl:for-each>
      </ul>
     
     
    </xsl:if>
  </xsl:template>
</xsl:stylesheet>