Wednesday, 30 November 2016

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.     
 

web configuration setting in asp.net web.config file

<configuration>
  <connectionStrings>
    <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Web.Extensions.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
        <add assembly="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Management, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
      </assemblies>
    </compilation>

    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login.aspx" timeout="2880"/>
    </authentication>
    <!--<membership>
            <providers>
                <clear/>
                <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/"/>
            </providers>
        </membership>
        <profile>
            <providers>
                <clear/>
                <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
            </providers>
        </profile>
        <roleManager enabled="false">
            <providers>
                <clear/>
                <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/"/>
                <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/"/>
            </providers>
        </roleManager>-->
    <customErrors mode="Off" defaultRedirect="~/GenericError_Message.aspx" />
    <pages>
      <controls>
        <add tagPrefix="cc2" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit"/>
        <add tagPrefix="cc1" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit"/>
        <add tagPrefix="asp" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit"/>
        <add tagPrefix="FTB" assembly="FreeTextBox" namespace="FreeTextBoxControls"/>
      </controls>
    </pages>
    <httpRuntime requestValidationMode = "2.0" />
    <siteMap enabled="true" defaultProvider="MyCustomSiteMap">
      <providers>
        <clear/>
        <add name="MyCustomSiteMap" type="MyCustomSiteMap"/>
      </providers>
    </siteMap>
    <!--<siteMap enabled="true" defaultProvider="MyCustomSiteMap">
      <providers>
        <clear/>
        <add name="MyCustomSiteMap" type="CustomSiteMap.MyCustomSiteMap"/>
      </providers>
    </siteMap>-->
    <globalization
     fileEncoding="utf-8"
     requestEncoding="utf-8"
     responseEncoding="utf-8"
     culture="en-US"
     uiCulture="de-DE"
    />
  
    <customErrors mode="RemoteOnly" defaultRedirect="ErrorPage.aspx">
      <error statusCode="522" redirect="Error522Page.aspx" />
      <error statusCode="404" redirect="ErrorPage.aspx" />
    </customErrors>
  
  </system.web>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <handlers>
      <add verb="GET" name="FTB"
                path="FtbWebResource.axd"
                type="FreeTextBoxControls.AssemblyResourceHandler, FreeTextBox" />
    </handlers>
    <defaultDocument>
      <files>
        <clear />
        <add value="Default.htm" />
        <add value="Default.asp" />
        <add value="index.htm" />
        <add value="index.html" />
        <add value="iisstart.htm" />
        <add value="default.aspx" />
        <add value="index.php" />
        <add value="index.aspx" />
      </files>
    </defaultDocument>
    <!-- Cross Domain Support but use when hosting on the production server not work on localhost -->
      <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>

How to read, select and update xml file in asp.net c#

Suppose we have  PopUp.xml file stored in Add_Data Folder and has following structure

<?xml version="1.0" encoding="utf-8"?>
<PopUp>
  <ProjectId>Zgv1wTgdGV</ProjectId>
  <ProjectName>Shree Siddhivinayak Green County</ProjectName>
  <Address>Yawat</Address>
  <ImageName>imgHomePopUp.jpg</ImageName>
  <InsertedBy>preetam@ranjeetdevelopers.com</InsertedBy>
  <InsertedOn>2016-10-24: 17:12:23.469</InsertedOn>
</PopUp>

to read and bind data to a dataset

 XmlTextReader xmlreader = new XmlTextReader(Server.MapPath("~/App_Data/PopUp.xml"));
            DataSet ds = new DataSet();
            ds.ReadXml(xmlreader);
            xmlreader.Close();

            if (ds.Tables.Count != 0)
            {
                RepeaterPopUp.DataSource = ds;
                RepeaterPopUp.DataBind();
            }


To Read and Update

XmlTextReader xmlreader = new XmlTextReader(Server.MapPath("~/App_Data/PopUp.xml"));
            DataSet ds = new DataSet();
            ds.ReadXml(xmlreader);
            xmlreader.Close();
            if (ds.Tables.Count != 0)
            {
               
                XmlDocument xDoc = new XmlDocument();
                string xmlFile = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/PopUp.xml");
                xDoc.Load(xmlFile);
                        //To Read Specific Node
                        //string nodeValue = xDoc.DocumentElement.SelectSingleNode("ProjectId").InnerText;
                        //Response.Write(nodeValue);

                StringBuilder ImageName = new StringBuilder();
                FileInfo FileInf = new FileInfo(FileUpload1.PostedFile.FileName);
                string ext = FileInf.Extension;
                ImageName.Append("imgHomePopUp");
                ImageName.Append(ext);
                //ImageName.Append(FileUpload1.PostedFile.FileName);
                string FImageName = ImageName.ToString();
                string path = "~/images/home-banner/" FImageName;             
                FileUpload1.PostedFile.SaveAs(MapPath(path));

                clsProject objProject = new clsProject();

                string projectId = ddlProject.SelectedValue;
                DataTable dt = objProject.Edit(projectId);
                string projectName = Convert.ToString(dt.Rows[0]["Title"]);
                string address = Convert.ToString(dt.Rows[0]["Address"]);

                 //To Read Specific Node
                xDoc.DocumentElement.SelectSingleNode("ProjectId").InnerText = projectId;
                xDoc.DocumentElement.SelectSingleNode("ProjectName").InnerText = projectName;
                xDoc.DocumentElement.SelectSingleNode("Address").InnerText = address;
                xDoc.DocumentElement.SelectSingleNode("ImageName").InnerText = FImageName;
                xDoc.DocumentElement.SelectSingleNode("InsertedBy").InnerText = (string) Session["sun"];
                xDoc.DocumentElement.SelectSingleNode("InsertedOn").InnerText = DateTime.Now.ToString("yyyy-MM-dd: HH:mm:ss.fff");
                xDoc.Save(xmlFile);
            }

clear or hide text of asp.net label contrl using javascript

copy the below snippets in head section of page and change the control id as per use

<script type="text/javascript">  
    function resetlabel() {
        document.getElementById('<%=Notification.ClientID%>').innerHTML= "";
        document.getElementById('<%=lblextMsg.ClientID%>').innerHTML = "";
    } setTimeout(resetlabel, 2000);
</script>

Tuesday, 7 June 2016

Bind Empty gridview using dataset or datatable with no record found message

Design Page ie ASPX Page


 <asp:GridView ID="gvnews" runat="server"
                AutoGenerateColumns="False" PageSize="10" Width="100%">
                <Columns>
                    <asp:TemplateField HeaderText="S.NO" ControlStyle-Width="50px">
                        <ItemTemplate>
                            <%# Container.DataItemIndex + 1 %>
                        </ItemTemplate>
                        <ControlStyle Width="50px" />
                    </asp:TemplateField>
                    <asp:BoundField HeaderText="Property Name" DataField="PropertyName" />
                    <asp:BoundField HeaderText="City" DataField="City" /> 
                </Columns>               
                <PagerSettings Mode="NumericFirstLast" PageButtonCount="5" FirstPageText="First"
                    LastPageText="Last" />            
 </asp:GridView>

 Code Behind ie ASPX.cs Page


 //define connection 
SqlConnection con= "your Connection";
con.Open();
//define your query;
string query="";
  SqlCommand cmd = new SqlCommand("query", con);
            DataTable dt = new DataTable();
            DataSet ds= new DataSet();
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            sda.Fill(dt);
sda.fill(ds);
            con.Close();
//using data set
public void bind_GridviewUsingDataSet()
{
       gvnews.DataSource = ds.Tables[0];
            if (ds.Tables[0].Rows.Count >0)
            {
                 gvnews.DataSource = ds;
                gvnews.DataBind();
            }
            else
            {
                ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
                gvnews.DataSource = ds;
                gvnews.DataBind();
                int columncount = gvnews.Rows[0].Cells.Count;
                gvnews.Rows[0].Cells.Clear();
                gvnews.Rows[0].Cells.Add(new TableCell());
                gvnews.Rows[0].Cells[0].ColumnSpan = columncount;
                gvnews.Rows[0].Cells[0].Text = "No Records Found";
                gvnews.Rows[0].Cells[0].ForeColor = Color.Red;            
            }

}

using DataTable
public void bind_GridviewUsingDataSet()
{

 GridView1.DataSource = dt;
            if (dt.Rows.Count > 0)
            {
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
            else
            {
                dt.Rows.Add(dt.NewRow());
                GridView1.DataSource = dt;
                GridView1.DataBind();
                int columncount = GridView1.Rows[0].Cells.Count;
                GridView1.Rows[0].Cells.Clear();
                GridView1.Rows[0].Cells.Add(new TableCell());
                GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
                GridView1.Rows[0].Cells[0].Text = "No Records Found";
                GridView1.Rows[0].Cells[0].ForeColor = Color.Red;
            }

}

This is my first post on this blog, if you find any mistake please let me know.