Wednesday, November 6, 2013

Download any file from website through console application in C#






Hi friends, in today example i would show you how to download any file from any website in C# through console application. For this we consider that we want to download some Excel file from http://www.testblog.com. As we see in the below snap, we have four link and we want to download those file through our console application.











For this first you have to download HtmlAgilityPack

  private static void DownloadXlsFiles(string filePath)  
     {  
       WebClient wc = new WebClient();  
       var sourceCode = wc.DownloadString("www.testblog.com");  
       HtmlDocument doc = new HtmlDocument();  
       doc.LoadHtml(sourceCode);  
       var node = doc.DocumentNode;  
       var nodes = node.SelectNodes("//a");  
       List<string> links = new List<string>();  
       foreach (var item in nodes)  
       {  
         var link = item.Attributes["href"].Value;  
         links.Add(link.Contains("http") ? link : "www.testblog.com" + link);  
       }  
       List<string> xlsLinks = new List<string>();  
       foreach (string s in links)  
       {  
         if (s.LastIndexOf(".xls") != -1)  
         {  
           xlsLinks.Add(s.ToString());  
         }  
       }  
       foreach (string file in xlsLinks)  
       {  
         string[] fileName = file.Split('/');  
         if (fileName.Length > 0)  
         {  
           WebClient webClient = new WebClient();  
           webClient.DownloadFile(file, filePath + fileName[fileName.Length - 1].ToString());  
           Console.WriteLine(fileName[fileName.Length - 1].ToString() + " download successfully");  
         }  
       }  
       Console.WriteLine("All files download successfully");  
     }  

Thursday, August 22, 2013

Call page method using javascirpt in asp.net



Call code behind method which have no parameter


Step 1: Put below script on your page


<script src="/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        function CallMethod() {
            GetTime();
        }
 
        function GetTime() {
           
           PageMethods.GetTime(GetTimeCallback, ErrorHandler, TimeOutHandler);
        }
        function TimeOutHandler(result) {
            alert("Timeout :" + result);
        }
        /// <summary>
        /// Callback function invoked on failure of the page method 
        /// </summary>
 
        function ErrorHandler(result) {
            var msg = result.get_exceptionType() + "\r\n";
            msg += result.get_message() + "\r\n";
            msg += result.get_stackTrace();
            alert(msg);
        }
        GetTimeCallback = function (result) {
            /// <summary>
            /// Is called when server sent result back
            /// </summary>
            /// <param name="result">
            /// Result of calling server method, 
            /// string - server time 
            /// </param>
            if (result) {
                $get("lblMessage").innerHTML = result;
            }
 
        }
    </script>



Step 2: Put below code in your aspx page


 <asp:ScriptManager EnablePageMethods="true" ID="MainSM" runat="server" ScriptMode="Release"
        LoadScriptsBeforeUI="true">
    </asp:ScriptManager>
    <asp:Label ID="lblMessage" runat="server" Text="" ClientIDMode="Static"></asp:Label><br/>
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" 
           OnClientClick="GetTime(); return false;" />


Step 3: Put below code in your aspx.cs page



        [System.Web.Services.WebMethod]
        public static string GetTime()
        {
            return DateTime.Now.ToString();
        }



Call code behind method which have parameter

Step 1: Put below script on your page


<script src="/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        function CallMethod() {
            GetTime();
        }
 
        function GetTime() {
           
           PageMethods.GetTime("test""12", GetTimeCallback, ErrorHandler, TimeOutHandler);

        }
        function TimeOutHandler(result) {
            alert("Timeout :" + result);
        }
        /// <summary>
        /// Callback function invoked on failure of the page method 
        /// </summary>
 
        function ErrorHandler(result) {
            var msg = result.get_exceptionType() + "\r\n";
            msg += result.get_message() + "\r\n";
            msg += result.get_stackTrace();
            alert(msg);
        }
        GetTimeCallback = function (result) {
            /// <summary>
            /// Is called when server sent result back
            /// </summary>
            /// <param name="result">
            /// Result of calling server method, 
            /// string - server time 
            /// </param>
            if (result) {
                $get("lblMessage").innerHTML = result;
            }
 
        }
    </script>



Step 2: Put below code in your aspx page


 <asp:ScriptManager EnablePageMethods="true" ID="MainSM" runat="server" ScriptMode="Release"
        LoadScriptsBeforeUI="true">
    </asp:ScriptManager>
    <asp:Label ID="lblMessage" runat="server" Text="" ClientIDMode="Static"></asp:Label><br/>
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" 
           OnClientClick="GetTime(); return false;" />


Step 3: Put below code in your aspx.cs page


[System.Web.Services.WebMethod]
        public static string GetTime(string abc, int i)
        {
            return i + "|" + abc + "|" + DateTime.Now.ToString();
        }

Monday, February 4, 2013

Remove foreach with LINQ Aggregate function to append some string

Hello friends,
Take an scenario where you want to append comma(,) with the string in foreach loop

Take an scenario where you want to append comma(,) 
with the string in foreach loop
 
string str=string.Empty;
foreach(ListItem li in cblPercentage.Items)
{
str += li.value + "," ;
}
 
Now you can remove this code with the LINQ Aggregate funtion

string str = cblPercentage.Items.Cast ().Where(item => item.Selected).Aggregate(string.Empty, (current, item) => current + (item.Value + ","));

Thursday, January 17, 2013

Custom paging for Gridview, Datalist, Datagrid and Repeater


Hi Friends,

Today i am going to demonstrate custom paging for Gridview, Datalist, Datagrid and Repeater.

Step 1: Create stored procedure named GetLog
Create Procedure GetLog
@Index INT=0,
@Size INT=0
AS
    BEGIN

            SELECT  * FROM (SELECT  ROW_NUMBER() OVER (ORDER BY Id ASC) as row,* FROM Log) tblTemp
                                    WHERE row between (@Index - 1) * @Size + 1 and @Index*@Size;
            SELECT COUNT(*) FROM Log;
    END


Step 2: Create class named Log.cs

public class Log
{
    public int Id { getset; }
    public DateTime Date { getset; }
    public string Logger { getset; }
    public string Message { getset; }
}

Step 3: Create Private Properties

#region Private Properties
        private int CurrentPage
        {
            get
            {
                object objPage = ViewState["_CurrentPage"];
                int _CurrentPage = 0;
                if (objPage == null)
                    _CurrentPage = 0;
                else
                    _CurrentPage = (int)objPage;
                return _CurrentPage;
            }
            set { ViewState["_CurrentPage"] = value; }
        }
        private int firstIndex
        {
            get
            {
                int _FirstIndex = 0;
                if (ViewState["_FirstIndex"] == null)
                    _FirstIndex = 0;
                else
                    _FirstIndex = Convert.ToInt32(ViewState["_FirstIndex"]);
                return _FirstIndex;
            }
            set { ViewState["_FirstIndex"] = value; }
        }
        private int lastIndex
        {
            get
            {
                int _LastIndex = 0;
                if (ViewState["_LastIndex"] == null)
                    _LastIndex = 0;
                else
                    _LastIndex = Convert.ToInt32(ViewState["_LastIndex"]);
                return _LastIndex;
            }
            set { ViewState["_LastIndex"] = value; }
        }
        #endregion
 
Step 4:  Create Methods

#region Method
 
        protected List<Log> GetList(int index)
        {
            var oManager = new IssueManager();
            DataSet dataSet = oManager.GetLog(index);
            ViewState["TotalPages"] = dataSet.Tables[1].Rows[0][0].ToStringSafe();
            return dataSet.Tables[0].ConvertToList<Log>();
        }
 
        /// <summary>
        /// Binding Main Items List
        /// </summary>
        private void BindItemsList(int index)
        {
            _PageDataSource.DataSource = GetList(index); ;
            _PageDataSource.AllowPaging = true;
            int pageSize = 15;
            _PageDataSource.PageSize = pageSize;
            _PageDataSource.CurrentPageIndex = 0;
 
            //this.lblPageInfo.Text = "Page " + (CurrentPage) + " of " + _PageDataSource.PageCount;
            hdnPageCount.Value = (CurrentPage + 1).ToStringSafe();
            int totalRecord = ViewState["TotalPages"].ToIntSafe();
            int lastPage = totalRecord / pageSize;
            int currentPageIndex = CurrentPage + 1;
            if (CurrentPage == 0)
            {
                this.lbtnFirst.Enabled = false;
                this.lbtnPrevious.Enabled = false;
                this.lbtnLast.Enabled = true;
                this.lbtnNext.Enabled = true;
            }
            else if (lastPage == currentPageIndex)
            {
                this.lbtnFirst.Enabled = true;
                this.lbtnPrevious.Enabled = true;
                this.lbtnLast.Enabled = false;
                this.lbtnNext.Enabled = false;
            }
            else
            {
                this.lbtnFirst.Enabled = true;
                this.lbtnPrevious.Enabled = true;
                this.lbtnLast.Enabled = true;
                this.lbtnNext.Enabled = true;
            }
            grvLog.DataSource = _PageDataSource;
            grvLog.DataBind();
            this.doPaging();
            if (_PageDataSource.DataSourceCount < 1)
            {
                tb_Pagging.Visible = false;
            }
        }
 
        /// <summary>
        /// Binding Paging List
        /// </summary>
        private void doPaging()
        {
            System.Data.DataTable dt = new System.Data.DataTable();
            dt.Columns.Add("PageIndex");
            dt.Columns.Add("PageText");
            firstIndex = CurrentPage - 5;
            int pageSize = 15;
            if (firstIndex < 0)
            {
                firstIndex = 0;
            }
            lastIndex = firstIndex + 15;
           
            int totalRecord = ViewState["TotalPages"].ToIntSafe();
            int remainder = totalRecord % pageSize;
            int lastPage;
            if (remainder == 0)
            {
                lastPage = totalRecord / pageSize;
            }
            else
            {
                lastPage = (totalRecord / pageSize) + 1;
            }
            if (lastIndex >= lastPage)
            {
                lastIndex = lastPage;
                if (CurrentPage+1 >= lastIndex)
                {
                    lbtnNext.Enabled = false;
                    lbtnLast.Enabled = false;
                }
                else
                {
                    lbtnNext.Enabled = true;
                    lbtnLast.Enabled = true;
                }
            }
            for (int i = firstIndex; i < lastIndex; i++)
            {
                System.Data.DataRow dr = dt.NewRow();
                dr[0] = i;
                dr[1] = i + 1;
                dt.Rows.Add(dr);
            }
            this.dlPaging.DataSource = dt;
            this.dlPaging.DataBind();
 
            if (dt.Rows.Count > 0)
            {
                if (dt.Rows.Count == 1)
                {
                    tb_Pagging.Visible = false;
                }
                else
                {
                    tb_Pagging.Visible = true;
                }
            }
        }
 
        #endregion
 
Step 5: Create Paged Datasource

#region PagedDataSource
 
        PagedDataSource _PageDataSource = new PagedDataSource();
 
        #endregion
 
Step 6: Create Pagging Events

#region PaggingEvents
 
        protected void lbtnFirst_Click(object sender, EventArgs e)
        {
            CurrentPage = 0;
            this.BindItemsList(CurrentPage + 1);
        }
        protected void lbtnPrevious_Click(object sender, EventArgs e)
        {
            CurrentPage -= 1;
            this.BindItemsList(CurrentPage + 1);
        }
        protected void lbtnNext_Click(object sender, EventArgs e)
        {
            CurrentPage += 1;
            this.BindItemsList(CurrentPage + 1);
        }
        protected void lbtnLast_Click(object sender, EventArgs e)
        {
            int pageSize = 15;
            int index;
            int count = ViewState["TotalPages"].ToIntSafe() % pageSize;
            if (count == 0)
            {
                CurrentPage = ViewState["TotalPages"].ToIntSafe() / pageSize;
            }
            else
            {
                CurrentPage = (ViewState["TotalPages"].ToIntSafe() / pageSize) + 1;
            }
            this.BindItemsList(CurrentPage);
            CurrentPage--;
        }
        protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName.Equals("Paging"))
            {
                CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());
                this.BindItemsList(CurrentPage + 1);
            }
        }
        protected void dlPaging_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            LinkButton lnkbtnPage = (LinkButton)e.Item.FindControl("lnkbtnPaging");
            if (lnkbtnPage.CommandArgument.ToString() == CurrentPage.ToString())
            {
                lnkbtnPage.Enabled = false;
                lnkbtnPage.Style.Add("fone-size""14px");
                lnkbtnPage.Font.Bold = true;
            }
        }
        #endregion

Step 7: Create Page load event

 #region Event
 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindItemsList(1);
            }
        }

Step 8: Now copy the html on aspx page

<div>
        <asp:GridView ID="grvLog" runat="server" AllowPaging="False" AutoGenerateColumns="False">
            <Columns>
                <asp:TemplateField HeaderText="ID">
                    <ItemTemplate>
                        <asp:Literal runat="server" ID="litID" Text='<%# Eval("Id") %>'></asp:Literal>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Date">
                    <ItemTemplate>
                        <asp:Literal runat="server" ID="litDate" Text='<%# Eval("Date") %>'></asp:Literal>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Logger">
                    <ItemTemplate>
                        <asp:Literal runat="server" ID="litLogger" Text='<%# Eval("Logger") %>'></asp:Literal>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:HiddenField ID="hdnPage" runat="server" Value="" />
        <asp:HiddenField ID="hdnPageCount" runat="server" Value="" />
        <table width="100%" id="tb_Pagging" runat="server">
            <tr>
                <td width="100%">
                    <table cellpadding="0" border="0">
                        <tr>
                            <td align="right">
                                <asp:LinkButton ID="lbtnFirst" Style="color: #1A75AC;" runat="server" ClientIDMode="Static"
                                    CausesValidation="false" OnClick="lbtnFirst_Click">First</asp:LinkButton>
                                &nbsp;
                            </td>
                            <td align="right">
                                <asp:LinkButton ID="lbtnPrevious" Style="color: #1A75AC;" runat="server" ClientIDMode="Static"
                                    CausesValidation="false" OnClick="lbtnPrevious_Click">Previous</asp:LinkButton>&nbsp;&nbsp;
                            </td>
                            <td align="center" valign="middle">
                                <asp:DataList ID="dlPaging" runat="server" RepeatDirection="Horizontal" OnItemCommand="dlPaging_ItemCommand"
                                    OnItemDataBound="dlPaging_ItemDataBound">
                                    <ItemTemplate>
                                        <asp:LinkButton ID="lnkbtnPaging" Style="color: #63182E; font-family: Arial; font-size: 14px;"
                                            runat="server" CommandArgument='<%# Eval("PageIndex") %>' CommandName="Paging"
                                            Text='<%# Eval("PageText") %>'></asp:LinkButton>&nbsp;
                                    </ItemTemplate>
                                </asp:DataList>
                            </td>
                            <td align="left">
                                &nbsp;&nbsp;<asp:LinkButton ID="lbtnNext" Style="color: #1A75AC;" runat="server"
                                    ClientIDMode="Static" CausesValidation="false" OnClick="lbtnNext_Click">Next</asp:LinkButton>
                            </td>
                            <td align="left">
                                &nbsp;
                                <asp:LinkButton ID="lbtnLast" runat="server" Style="color: #1A75AC;" CausesValidation="false"
                                    ClientIDMode="Static" OnClick="lbtnLast_Click">Last</asp:LinkButton>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
    </div>
Blogarama - The Blog Directory