Wednesday, 30 November 2016

Show Image Loader while processing data in Asp.net C# using Ajax UpdatePanel Animation Extender and JavaScript

<script type="text/javascript">
     function InProgress() {
         var panelProg = $get('divProgress');
         panelProg.style.display = '';

         var lbl = $get('<%# this.lblText.ClientID %>');
         lbl.innerHTML = '';
     }

     function onComplete() {
         var panelProg = $get('divProgress');
         panelProg.style.display = 'none';
     }     
    </script>
    <style type="text/css">
        .popup
        {
            border: 0px solid #6b6a63;
            width: 100%;
            height: 100%;
            position: fixed;
            background-color: rgba(0, 0, 0, .1);
            z-index: 99999;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
        }
        .prgimg
        {
 
           top: 0;

            bottom: 0;
            left: 0;
            right: 0;
            margin: 35% 0 0 0%;
            z-index: 9999999999;
        }
    </style>

========================================================================================
 <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="full" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
        <asp:Label ID="lblText" runat="server" />
                <div id="divProgress" style="display:none;" class="popup">
                     <asp:Image ID="LoadingImage" runat="server" ImageUrl="~/images/loader.gif" />                   
                </div>       
        </ContentTemplate>
                <Trigger>
                </Trigger>
    </asp:UpdatePanel>
===========================
 <asp:UpdatePanelAnimationExtender ID="UpdatePanelAnimationExtender1" TargetControlID="full" runat="server">
        <Animations>
            <OnUpdating>                     
               <Parallel duration="0">
                    <ScriptAction Script="InProgress();" />
                    <EnableAction AnimationTarget="Button1" Enabled="false" />     
                    <EnableAction AnimationTarget="LinkButton1" Enabled="false" />        
                    <EnableAction AnimationTarget="LinkButton2" Enabled="false" />              
                </Parallel>
            </OnUpdating>
            <OnUpdated>
                <Parallel duration="0">              
                    <ScriptAction Script="onComplete();" />
                    <EnableAction AnimationTarget="Button1" Enabled="true" />
                    <EnableAction AnimationTarget="LinkButton1" Enabled="true" />        
                    <EnableAction AnimationTarget="LinkButton2" Enabled="true" />   
                </Parallel>
            </OnUpdated>
        </Animations>
        </asp:UpdatePanelAnimationExtender>


split , separated string and bind in gridview in asp.net c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.NetworkInformation;
using System.Data.SqlClient;
using System.Data;
using System.Text;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Runtime.InteropServices;
using System.Management;
using System.Security.Cryptography;

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {

            generatedatatable();
           
        }
    }

    public void generatedatatable()
    {
        try
        {
                  method 1: separate comma and pipe ("," and "|") attached string
            ArrayList List = new ArrayList();             
            //string TstStr = "1,dt3435,26/5/2012 ~ 2,dt738,27/5/2012 ~ 3,dt892,26/5/2012";
            string query = "Select Specification From Menu_new_date where S_no='54'";
            string TstStr = Convert.ToString(connection.scalar(query));
            string[] SplittedString = TstStr.Split('|');
            foreach (string str in SplittedString)
            {
                string ConcatStr = "";
                string[] SubSplit = str.Trim().Split(',');
                foreach (string s in SubSplit)
                {
                    ConcatStr = s " ";
                }
                List.Add(ConcatStr);
            }

            DataTable dt = new DataTable();
            DataColumn dc = new DataColumn("Nutrition", typeof(string));
            //DataColumn dc1 = new DataColumn("Quantity", typeof(string));      
            dt.Columns.Add(dc);
            //dt.Columns.Add(dc1);
            for (int i = 0; i < List.Count; i )
            {
                dt.Rows.Add();
                dt.Rows[i][0] = List[i];
            }
            ------------------------------------------------------------------------------------------

                Method:2  separate comma  (",") attached string in one row with dynamically crate no of column as per the comma
               
            ArrayList List = new ArrayList();
            //string TstStr = "1,dt3435,26/5/2012 ~ 2,dt738,27/5/2012 ~ 3,dt892,26/5/2012";
            string query = "Calories 212 Kcal,Total fat 5.7 g,Saturated fat 0.8 g,Polyunsaturated fats 1 g,Monounsaturated fats 3.4 g,Total                 carbohydrate 25.2 g,Dietary fibre 4.3 g,Sugars 2.3 g,Protein 17.4 g";
            //string TstStr = Convert.ToString(connection.scalar(query));
            string TstStr = query;
            string abc="";
            string[] SplittedString = TstStr.Split(',');
            foreach (string str in SplittedString)
            {
                 abc =str;
                 List.Add(abc);
            }

            DataTable dt = new DataTable();
            //DataColumn dc = new DataColumn("Nutrition", typeof(string));
            //DataColumn dc1 = new DataColumn("Quantity", typeof(string));      
           
            //dt.Columns.Add(dc1);
            dt.Rows.Add();
            for (int i = 0; i < List.Count; i )
            {
                DataColumn dc = new DataColumn("Nutrition" i, typeof(string));
                dt.Columns.Add(dc);
               
               
                dt.Rows[0][i]= List[i];
              
             
            }

            GridView1.DataSource = dt;
            GridView1.DataBind();
            ------------------------------------------------------------------------------------------------

                Method:3  separate comma  (",") attached string in multiple row

            ArrayList List = new ArrayList();
            string TstStr = "1,dt3435,26/5/2012 ~ 2,dt738,27/5/2012 ~ 3,dt892,26/5/2012";
            string query = "Calories 212 Kcal,Total fat 5.7 g,Saturated fat 0.8 g,Polyunsaturated fats 1 g,Monounsaturated fats 3.4 g,Total                 carbohydrate 25.2 g,Dietary fibre 4.3 g,Sugars 2.3 g,Protein 17.4 g";
            string TstStr = Convert.ToString(connection.scalar(query));
            string TstStr = query;
            string abc = "";
            string[] SplittedString = TstStr.Split(',');
            foreach (string str in SplittedString)
            {
                abc = str;
                List.Add(abc);
            }

            DataTable dt = new DataTable();
            DataColumn dc = new DataColumn("Nutrition", typeof(string));
            DataColumn dc1 = new DataColumn("Quantity", typeof(string));      

          
            dt.Columns.Add(dc);
            for (int i = 0; i < List.Count; i )
            {                             
                dt.Rows.Add();
                dt.Rows[i][0] = List[i];
            }
                //create gridview dynamically and add this gridview to any div where to show data
            GridView grid = new GridView();
            grid.DataSource = dt;
            grid.DataBind();
            nutri.Controls.Add(grid);
               
        //bind splitted string to available gridview
            GridView1.DataSource = dt;
            GridView1.DataBind();

                        
Nutrition
Calories 212 Kcal
Total fat 5.7 g
Saturated fat 0.8 g
Polyunsaturated fats 1 g
Monounsaturated fats 3.4 g
Total carbohydrate 25.2 g
Dietary fibre 4.3 g
Sugars 2.3 g
Protein 17.4 g


            --------------------------------------------------------------------------------------------------------
         Method:4  separate  comma and pipe ("," and "|") attached string in multiple row
            DataTable values = new DataTable();
            values.Columns.Add("Nutrition", typeof(string), null);
            values.Columns.Add("Quantity", typeof(string), null);

            string query = "Select Specification From Menu_new_date where S_no='54'";
            string TstStr = Convert.ToString(connection.scalar(query));
            values = TstStr.Split('|').Select(s =>
            {
                var fields = s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var row = values.NewRow();
                if (fields.Length == 2)
                {
                    row[0] = fields[0].Trim();
                    row[1] = fields[1].Trim();                  
                }
                return row;
            }).CopyToDataTable();

            GridView1.DataSource = values;
            GridView1.DataBind();
        }
        catch (Exception ex)
        {
            Label1.Text= ex.Message;
        }
    }
   
}

Automatically update the copyright year in html page in asp.net

Replace Year with below line

<%= DateTime.Now.Year.ToString() %>

How to seach in gridview using key up method like table in html


// Add a gridview to the aspx page and a textbox for search. bind the gridview for populating the data

Put this java script in head of the aspx page

  <script type="text/javascript">
        function filter2(phrase) {
            var words = phrase.value.toLowerCase().split(" ");
            var table = document.getElementById("<%=GridView1.ClientID %>");
            var ele;
            for (var r = 1; r < table.rows.length; r ) {
                ele = table.rows[r].innerHTML.replace(/<[^>] >/g, "");
                var displayStyle = 'none';
                for (var i = 0; i < words.length; i ) {
                    if (ele.toLowerCase().indexOf(words[i]) >= 0)
                        displayStyle = '';
                    else {
                        displayStyle = 'none';
                        break;
                    }
                }
                table.rows[r].style.display = displayStyle;
            }
        }
    </script>

Now add this function "keyup" in the texbox which will be used to enter the keyword like this

 <asp:TextBox ID="TextBox2" runat="server" class="form-control" onkeyup="filter2(this)"></asp:TextBox>

Pagination in Repeater Control in ASP.NET C#

in aspx page drag and drop a repeater control from toolbox

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Perfect Pagination With Repeater and ASP.Net C#</title>
    <link href="admin/css/stylesheet.css" rel="stylesheet" type="text/css" />
   
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="MainScriptManager" runat="server" />
    <asp:UpdatePanel ID="pnlHelloWorld" runat="server">
        <ContentTemplate>
            <div>
                <asp:Repeater ID="rptResult" runat="server">
                    <HeaderTemplate>
                        <table class="mGrid">
                            <tr class="mGrid table_head">
                                <th>
                                    ID
                                </th>
                                <th>
                                    Name
                                </th>
                                <th>
                                    Address
                                </th>
                                <th>
                                    Created Date
                                </th>
                            </tr>
                    </HeaderTemplate>
                    <ItemTemplate>
                        <tr>
                            <td>
                                <%#Eval("PageId") %>
                            </td>
                            <td>
                                <%#Eval("PageName") %>
                            </td>
                            <td>
                                <%#Eval("Section") %>
                            </td>
                            <td>
                                <%#Eval("Department") %>
                            </td>
                        </tr>
                    </ItemTemplate>
                    <FooterTemplate>

                         <tr>
                 <td colspan="4"><asp:Label Visible='<%#bool.Parse((Repeater1.Items.Count==0).ToString())%>' runat="server"    ID="lblNoRecord" Text="No Record Found!" ForeColor="Red"></asp:Label></td>
                </tr>
                        </table>
                    </FooterTemplate>
                </asp:Repeater>
            </div>
            <div style="margin-top: 20px;">
            <asp:Label ID="lblpage" runat="server" Text=""></asp:Label>
                <table>
                    <tr class="mGrid table_head">                      
                        <td>
                            <asp:LinkButton ID="lbFirst" runat="server" OnClick="lbFirst_Click">First</asp:LinkButton>
                        </td>
                        <td>
                            <asp:LinkButton ID="lbPrevious" runat="server" OnClick="lbPrevious_Click">Previous</asp:LinkButton>
                        </td>
                        <td>
                            <asp:DataList ID="rptPaging" runat="server" OnItemCommand="rptPaging_ItemCommand"
                                OnItemDataBound="rptPaging_ItemDataBound" RepeatDirection="Horizontal" RepeatLayout="Table">
                                <ItemTemplate>
                                    <asp:LinkButton ID="lbPaging" runat="server" CommandArgument='<%# Eval("PageIndex") %>'
                                        CommandName="newPage" Text='<%# Eval("PageText") %>'>
                                    </asp:LinkButton>
                                </ItemTemplate>
                            </asp:DataList>
                        </td>
                        <td>
                            <asp:LinkButton ID="lbNext" runat="server" OnClick="lbNext_Click">Next</asp:LinkButton>
                        </td>
                        <td>
                            <asp:LinkButton ID="lbLast" runat="server" OnClick="lbLast_Click">Last</asp:LinkButton>
                        </td>
                       
                    </tr>
                </table>
            </div>
        </ContentTemplate>
    </asp:UpdatePanel>
    </form>
</body>
</html>


in Code Behind [aspx.cs] page

readonly PagedDataSource _pgsource = new PagedDataSource();
        int _firstIndex, _lastIndex;
        private int _pageSize = 10;
        private int CurrentPage
        {
            get
            {
                if (ViewState["CurrentPage"] == null)
                {
                    return 0;
                }
                return ((int)ViewState["CurrentPage"]);
            }
            set
            {
                ViewState["CurrentPage"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack) return;
            BindDataIntoRepeater();
        }

        // Get data from database/repository
        static DataTable GetDataFromDb()
        {
            string query = "Select * from Page";
            DataTable dt = connection.getDatatbl(query);
            return dt;
        }

        // Bind PagedDataSource into Repeater
        private void BindDataIntoRepeater()
        {
            var dt = GetDataFromDb();
            _pgsource.DataSource = dt.DefaultView;
            _pgsource.AllowPaging = true;
            // Number of items to be displayed in the Repeater
            _pgsource.PageSize = _pageSize;
            _pgsource.CurrentPageIndex = CurrentPage;
            // Keep the Total pages in View State
            ViewState["TotalPages"] = _pgsource.PageCount;
            // Example: "Page 1 of 10"
            lblpage.Text = "Page " (CurrentPage 1) " of " _pgsource.PageCount;
            // Enable First, Last, Previous, Next buttons
            lbPrevious.Enabled = !_pgsource.IsFirstPage;
            lbNext.Enabled = !_pgsource.IsLastPage;
            lbFirst.Enabled = !_pgsource.IsFirstPage;
            lbLast.Enabled = !_pgsource.IsLastPage;

            // Bind data into repeater
            rptResult.DataSource = _pgsource;
            rptResult.DataBind();

            // Call the function to do paging
            HandlePaging();
        }

        private void HandlePaging()
        {
            var dt = new DataTable();
            dt.Columns.Add("PageIndex"); //Start from 0
            dt.Columns.Add("PageText"); //Start from 1

            _firstIndex = CurrentPage - 5;
            if (CurrentPage > 5)
                _lastIndex = CurrentPage 5;
            else
                _lastIndex = 10;

            // Check last page is greater than total page then reduced it
            // to total no. of page is last index
            if (_lastIndex > Convert.ToInt32(ViewState["TotalPages"]))
            {
                _lastIndex = Convert.ToInt32(ViewState["TotalPages"]);
                _firstIndex = _lastIndex - 10;
            }

            if (_firstIndex < 0)
                _firstIndex = 0;

            // Now creating page number based on above first and last page index
            for (var i = _firstIndex; i < _lastIndex; i )
            {
                var dr = dt.NewRow();
                dr[0] = i;
                dr[1] = i 1;
                dt.Rows.Add(dr);
            }

            rptPaging.DataSource = dt;
            rptPaging.DataBind();
        }

        protected void lbFirst_Click(object sender, EventArgs e)
        {
            CurrentPage = 0;
            BindDataIntoRepeater();
        }
        protected void lbLast_Click(object sender, EventArgs e)
        {
            CurrentPage = (Convert.ToInt32(ViewState["TotalPages"]) - 1);
            BindDataIntoRepeater();
        }
        protected void lbPrevious_Click(object sender, EventArgs e)
        {
            CurrentPage -= 1;
            BindDataIntoRepeater();
        }
        protected void lbNext_Click(object sender, EventArgs e)
        {
            CurrentPage = 1;
            BindDataIntoRepeater();
        }

        protected void rptPaging_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (!e.CommandName.Equals("newPage")) return;
            CurrentPage = Convert.ToInt32(e.CommandArgument.ToString());
            BindDataIntoRepeater();
        }

        protected void rptPaging_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            var lnkPage = (LinkButton)e.Item.FindControl("lbPaging");
            if (lnkPage.CommandArgument != CurrentPage.ToString()) return;
            lnkPage.Enabled = false;          
            lnkPage.Attributes.Add("style", "text-align:center;");
        }

Bind dropdown control in asp.net c# from database

protected void bind_servicestype()
    {

        try
        {
            // bind dropdown from database
            string query="select Deposit_Type from Add_Deposit_Type";
            DataSet ds = connection.dataadapter(query);
            DropDownList1.DataSource = ds.Tables[0];
            DropDownList1.DataTextField = "Deposit_Type";
            DropDownList1.DataValueField = "Deposit_Type";
            DropDownList1.DataBind();
          
            // insert a default value in the dropdown
            DropDownList1.Items.Insert(0, new ListItem("---------Select--------", "0"));
        }
        catch (Exception EXP)
        {
            Response.Write(EXP.Message);
        }

Publish or Deploy website in our local machine using asp.net

Here I will explain how to publish or deploy the website in local machine. To publish website first we need to check whether IIS installed in our local machine or not and whether that IIS working properly or not because sometimes IIS will not work properly even that IIS already installed in our local machine for that reason we need to check all these conditions before going to publish or deploy our website in local machine.

After that now open the application in visual studio whatever the application we need publish.

1.  Open the website in that top we have options Build click on that you will find Publish website click on that it will open one wizard in that it will ask target location i.e., the place to save the published application (ex: Create one folder on desktop or any location give that path by using browse button beside of that textbox).

2.   Click on publish it publish all the files into target folder i.e., target location.

3.   Now go to the folder whatever we have given in target location copy that folder and place it in wwwroot folder(path of that folder is C:\Inetpub\wwwroot)

4.   Now open the Run in StartMenu and type inetmgr  and Click Enter it will automatically redirect to IIS

5.   Open the local computer in that open the websites after that open the Default website in that you will find our website because you have already placed our published website in to wwwroot folder. wwwroot folder is the default path for IIS if we place any websites into wwwroot folder it will automatically displays under Default Website

6.   Click on the your website right side it will display all of your published pages select whatever the page first you need to run right click on that and click browse it will display your published website.

7.   At that time if you get any error please right click on website in Default Website goes to Properties and click on Create button and click Ok button. Now browse your default page.

This is the one way to publish the website
=============================================================================================
Another way is

1.   Type inetmgr in run command it will open IIS

2.   Click on local computer in that open the websites after that open the Default website and right click on Default website in that click New option in that select Virtual Directory click on that one wizard will open click on NEXT after that it will ask Alias name give some name to display in Default website click Next now it will ask path for website give the path of your website whatever the application you to want publish or deploy after that click Next in that select Read, Run Scripts click next click finish button.

3.   Now your website has been published open that website in Default website select the Default page right click on that select browse option now your website will display.

4.   At that time if you get any error please right click on website in Default Website goes to Properties and click on Create button and click Ok button. Now browse your default page.

5.   Then make the website as application by right click on the website.

6.   Right click on the application pool of the inetmgr(IIS manager) and right click on DefaultAppPoolgo in App Pool Part. Choose  Advance Setting and  go to Process Model Category and select
Identitty. click on browse button and select Built-In Account and set the dropdown value as NetworkService.

Create a user in the database as NT AUTHORITY\NETWORK SERVICE with same login name. it will make the website accessible through out the lan by typin the ip address of the hosted
machine on netwok computer.
==============================================================================================================================================

ADO DOT NET, Connection, Command and DataReader object




ADO DOT NET (Active Data Object)

[DEFINATION] It’s a component in dot net framework which helps us to fetch data from different data source to c# or from C# code to data sources.

ADO DOT NET comprises of 6 components:


1.      Connection- Compulsory
2.      Command - Compulsory
3.      Data Reader
4.      Data Adapter
5.      Data Set
6.      Data View



In these 6 components 2 components are compulsory (connection and command)


Connection Object - this object is needed to connect to data source like Sql-Server, Oracle, MySql etc to use this object at least two things are required.
a.       Data source- where database is located either in local host or on remote host.
b.      Security credentials -like windows authentication, user id and password.

    Command Object- Sql syntaxes are written here and it helps to execute the Sql query. 

    Data Reader -  [Connected, Read Only and Forward Only Record Set]
Data Adapter - It’s bridge between data source and dataset. It actually fills the dataset with data coming from database. 

Data Set It’s a disconnected record set which can be browsed forth and back direction and can also be updated.

Difference B/W DataReader and DataSet
#
DataReader                                                 DataSet

1.
Its collection of connected records                  Its collection of disconnected records.

2.
It can only be accessed in forward mode         It can be accessed in forward and backward mode.

3.
Records in DataReader cannot be updated      Records in DataSet can be updated.



Dispose() Vs Finalize()



Dispose() Method


  1. This dispose method will be used to free unmanaged resources like files, database connection etc.
  2.  To clear unmanaged resources we need to write code manually to raise dispose() method.
  3. This Dispose() method belongs to IDisposable interface.
  4.  If we need to implement this method for any custom classes we need to inherit the class from IDisposable interface.
  5.  It will not show any effect on performance of website and we can use this method whenever we want to free objects immediately.


Finalize() Method


  1. This method also free unmanaged resources like database connections, files etc.
  2. It is automatically raised by garbage collection mechanism whenever the object goes out of scope.
  3.  This method belongs to object class.
  4.   We need to implement this method whenever we have unmanaged resources in our code and make sure these resources will be freed when garbage collection process done.
  5.   It will show effect on performance of website and it will not suitable to free objects immediately.