Create URL dynamically in ASP.NET

Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags with Leave a comment on Create URL dynamically in ASP.NET

Utility program to find that current connection is secured or not, connection is http or https. Create dynamic URL in ASP.NET. Example of Page.ResolveUrl() in ASP.Net.

Hi friend,

I am writing this article after very long duration. Have lots of tips to share from my toolbox, so here few about the dynamic creation of URL in ASP.NET:

lets say, you have to register the javascript file from code behind, then you may need a full path for that js file in format “http://yourdomain/jsfolder/jsfilename”

one way to achieve this is like :

"http://" Request.ServerVariables["HTTP_HOST"] + "/jsfolder/jsfilename.js";

In above snap you can see that HTTP_HOST is used. This server variable returns the address of your domain. Still, above code is not 100% functional.protocol may be http or https.

Continue reading “Create URL dynamically in ASP.NET”

Add CSS Programatically in ASP.NET

Author posted by Jitendra on Posted on under category Categories ASP.NET, Web Technology and tagged as Tags , with Leave a comment on Add CSS Programatically in ASP.NET

Tutorial on adding the CSS file dynamically in ASP.NET and C# / VB.Net

We Can set (Register) the Javascript file in ASP.NET but there is no such method for the CSS. So i have decided to write the article on how to set the CSS path dynamically in ASP.NET and C#.

Continue reading “Add CSS Programatically in ASP.NET”

Response.Flush in ASP.NET

Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags with Leave a comment on Response.Flush in ASP.NET

Usage of Response.Flush method in ASP.NET, its disadvantage and advantage of buffering in IIS.

IIS5 enables buffering by default, therefore all the output from your ASP is actually sent to the browser only when the page completes its processing. In many cases this approach improves the overall processing speed, and indirectly makes for a more scalable site.

However, buffering has two minor defects:

  1. The end user might perceive a loss in speed, because she won’t see any output until the page is complete, and
  2. Buffered output has to be maintained on the server, therefore your ASP application is going to take more memory than it would do if buffering were disabled. On server machines with an inadequate amount of memory, large HTML pages can reduce the overall performance.

Continue reading “Response.Flush in ASP.NET”

Row expand collapse using jquery and Ajax

Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags , , , , , with 3 Comments on Row expand collapse using jquery and Ajax

Using JQuery and Ajax to expand and collapse the row in ASP.NET

This article describes how to expand and collapse rows of a GridView or Table and showing data details using Jquery and Ajax

Introduction:

Now day’s , important issue with web applications is how quick a wed page is rendered  and how it is animated or  visualized

So for quick reply from server Ajax is the solutions and for some visualizations with server side response we mostly use jquery or javascript.
I this article, for exp

anding , collapsing and  adding details to gridview row we are going to use AJAX to make call to server and we will visualized it using jquery.

Aim

1. Getting details of product  by extracting details at the next to current row and before second    one.

2. Visualizing  the expanding of rows.

3. No server side postback.

4. Using GridView Control to bind data and simple data binding to table using scriptlet.

Using  Jquery Code

Expanding Row :

For expanding any row, we need to create an new row  with the serverside details  and then we will add it to the next of current row

Ajax JQuery Row Expand Collapse

var trindex=0;	//trindex hold row index created by jquery
$("tr").click(function() {
if ($(this).find("td:first").length > 0) { //check whether it is header or content row
//row index increment to assign new row id everytime
trindex++;
//create a row with td colspan 3 to show product description
var row= '><td class="currRow" colspan="3" ><
div id="did"><img id="imagepath" src=""
style="height: 81px; width: 104px" />  Description :<
span id="des">sd</span><p>Cost :<
span id="cost">sd</span></p></div></td></tr>';

//adding animation to row
var newRow = $("<tr id=tr"+ trindex + row).animate({
height: "140px",
opacity: 0.25,
}, 500);
//adding row to existing table
$(this).after(newRow);
Collapsing  Row :

At the same moment we expand any row, we collapse previous created row, so we need to remember the previous created rowIndex or it’s id.

Ajax JQuery Row Expand Collapse

$("#"+rowName).find('td').removeClass('currRow').addClass('hideRow');
$("#"+rowName).animate({
    height: "0px",
    opacity: 0.25,
    }, 1000, function() {
$("#"+rowName).remove();</pre>
<h5>Ajax Call to the server :</h5>
For getting the full details about our shortly highlighted product, we need to make a asynchronous call to
server using AJAX. We are passing some key values to server(product Id) to extract the resultset.
<pre>$.ajax({
       type: "POST",
       url: "WebService.asmx/GetDetails",   //webserviceName/methodName
       data: "{'name': '" + $(this).find("td span").text() + "'}",  //passing values to webservice(productid)
       contentType: "application/json; charset=utf-8",
       dataType: "json",
       success: function(msg) {
       //extrating response data to newly created row
       $("#tr"+trindex ).find("td #did p #cost").text(msg.d.id );
       $("#tr"+trindex ).find("td #did  #des").text(msg.d.order);
       $("#tr"+trindex ).find("td #did #imagepath").attr('src', msg.d.order);
//$("#myImage").attr("src", "path/to/newImage.jpg");
       },
       error: FailedMessage     //showing error message if failure
       });
Using The WebService.cs

Programmable application logic accessible via standard Web protocols.We are using webservice to extract data from database using jquery Ajax call.  CollectData class to hold extracted details from db.

public class CollectData
{
        public string cost { get; set; }
        public string imagePath { get; set; }
        public string description { get; set; }
}

Simple queries to the database via WebMethod

[WebMethod()]
    public CollectData GetDetails(string name)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].
        ConnectionString);
        SqlCommand cmd = new SqlCommand("Select cost, imagePath, description from Products where ProductId='" +
        name + "'",con);
        SqlDataReader data;
        CollectData c = new CollectData();
        try
        {
            con.Open();
            data=cmd.ExecuteReader();
            if (data.Read())
            {
                c.cost= data[0].ToString();
                c.imagePath = data[1].ToString();
                c.description = data[2].ToString();
                return c;
            }
            else
            {
                c.cost = "N/A";
                c.imagePath = "N/A";
                c.description = "N/A";
                return c;
            }
        }
        catch (Exception ex)
        {
            c.cost = "N/A";
            c.imagePath = "N/A";
            c.description = "N/A";
            return c;
        }

    }

Conclusion :

We have mixed up Jquery, Ajax, server Control(Gridview ) to get quick and visualized output. Result can be little bit change as per the browsers.

Uploaded on Codeproject

Download Demo Article

Telerik RadWindow Pop up Problem in Chrome and safari

Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags , with 1 Comment on Telerik RadWindow Pop up Problem in Chrome and safari

Telerik Popup Window Height is not set in Safari and Chrome (Apple Webkit Browsers)

Recently i have faced one issue with display of Telerik Rad Window on Apple Webkit browsers (Chrome and safari).

The problem was, the window appeared cropped in Chrome and safari. the height attribute of body tag wasn’t working properly.

After lots of trial and googling I found one work around to solve this issue.

Set the contentFrame after show of Telerik pop up from Client side to 100%, and it will save your time. 🙂

 var oWindow = $find("<%=radAddCD.ClientID%>;");
 if(oWindow)
 {
 oWindow.show();
 var contentFrame = oWindow.get_contentFrame();
 contentFrame.style.height = "100%";
 return false;
 }

Clear ASP page cache – Page_Load() firing multiple time in RadWindow Popup

How to prevent the multiple Page load event in case Telerik Rad Window Popup is used and Clear ASP page cache.

Setting ReloadOnShow property of RadWindow for Popup to true causes its Page_load to be executed multiple times hence redundant multiple database calls causing to some extent of performance hit.

ReloadOnShow needs to be  set to true since page_load/refresh of Popup wasn’t firing on subsequent opens.

Solution

We can set ReloadOnShow to false and use alternative code in page_load as following in C#:

below code will clear the cache of ASPX page and thus reloaded every time in browser.

Note : you should run these statement before sending any HTML to the user. If in doubt, use Respose.Buffer = True to buffer all html

Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoServerCaching();
Response.Cache.SetNoStore();
Response.AppendHeader("Pragma", "no-cache");
Response.Expires = -1;
Response.CacheControl = "no-cache";

Find all possible solution at this URL

Difference between $find and $get Methods

Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags , , with Leave a comment on Difference between $find and $get Methods

What is Difference between $find() and $get() Methods in ASP.NET

$get is used to get a reference to a DOM element. It is an alias for Sys.UI.DomElement.getElementById:

var myLabel = $get(‘myLabel’);

$find is an alias for Sys.Application.findComponent() and it’s used to get a reference to a particular component, given its id.

How to get DOM element using $find

var lnkAddNew = $find("CntrlID");
if(lnkAddNew)
{
    lnkAddNew.get_element().style.display = '';
}

Selecting and Sorting in DataTable – ASP.net C#

Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags with Leave a comment on Selecting and Sorting in DataTable – ASP.net C#

Demonstrates that how to select and sort the Datatable in ASP.Net , C#

DataTable in C# have very reach features to store the data in Tabular forms and also to display sorted or selected data on predefined category. Below i have provided the source code which demonstrates that how to select and sort the Datatable in ASP.Net.

Sorting and Selecting DataTable in ASP

below is the snap of C# File:

 public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable dt = prepareTable();
            GridView1.DataSource = dt;
            GridView1.DataBind();

            dt.DefaultView.Sort = "DOB ASC";
            GridView2.DataSource = dt;
            GridView2.DataBind();

            dt.DefaultView.Sort = "Age DESC";
            GridView3.DataSource = dt;
            GridView3.DataBind();

            dt.DefaultView.Sort = "Id DESC, Age ASC";
            GridView4.DataSource = dt;
            GridView4.DataBind();

            DataRow[] dtRows = dt.Select("Age > 20", "Age ASC");
            DataTable dt1 = new DataTable();
            dt1.Columns.Add("Id", typeof(int));
            dt1.Columns.Add("Name", typeof(string));
            dt1.Columns.Add("Age", typeof(int));
            dt1.Columns.Add("DOB", typeof(DateTime));

            foreach (DataRow dr in dtRows)
            {
                dt1.Rows.Add(dr[0], dr[1], dr[2],dr[3]);
            }

            GridView5.DataSource = dt1;
            GridView5.DataBind();
        }

        /// <summary>
        /// Prepares the table for Data.
        /// </summary>
        /// <returns></returns>
        private DataTable prepareTable()
        {
            DataTable rs = new DataTable();
            rs.Columns.Add("Id", typeof(int));
            rs.Columns.Add("Name", typeof(string));
            rs.Columns.Add("Age", typeof(int));
            rs.Columns.Add("DOB", typeof(DateTime));

            AddItems(rs,1,"Tuiya",24,DateTime.Now.AddYears(-20));
            AddItems(rs, 2, "Sonu", 20, DateTime.Now.AddYears(-21));
            AddItems(rs, 4, "Rohan", 19, DateTime.Now.AddYears(-22));
            AddItems(rs, 4, "Manoranjan", 27, DateTime.Now.AddYears(-23));
            AddItems(rs, 1, "Santosh", 24, DateTime.Now.AddYears(-20));

            return rs;
        }

        /// <summary>
        /// Adds the items.
        /// </summary>
        /// <param name="rs">The DataTable.</param>
        /// <param name="id">The id.</param>
        /// <param name="name">The name.</param>
        /// <param name="age">The age.</param>
        /// <param name="dob">The dob.</param>
        private static void AddItems(DataTable rs,int id,string name,int age,DateTime dob)
        {
            DataRow dtRow = rs.NewRow();
            dtRow[0] = id;
            dtRow[1] = name;
            dtRow[2] = age;
            dtRow[3] = dob;
            rs.Rows.Add(dtRow);
        }
    }

Working Demo of DataTable

Tracing ASP.NET Website

Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags , , with 1 Comment on Tracing ASP.NET Website

Demonstrates that how to Trace ASP.NET web applications

In ASP.NET there two types of Tracing

  • Application Level
  • Page Level

Page level Tracing takes the precedence over the Application Level tracing.

Lets start with creating new website.

In web.config add following entries to enable Application level tracing below System.web element.

<system.web>
<trace
pageOutput="true"
enabled="true"
requestLimit="10"
localOnly="false"
mostRecent="true"
traceMode="SortByTime"
/>
</system.web>

where:

pageOutput=”true” – add the tracing information at the bottom of the ASPX page.

localOnly=”false” – tracing will be available to any web page.

requestLimit=”10″ – How many request should be saved on the server.

mostRecent=”true” – whether or not display the recent tracing information if the request reach at the limit.

After adding above tag in web.config, the output of ASP.NET page will look like:

ASP.NET Tracing Output

Here you can see much of informations displayed like SessionId, Request Status, Controls available on that page,  All the events of the page with start and end time etc and thus you can figure out the performance of your web application.

No Trace for a particular Page

Create a web page and in aspx file and at header write the tag Trace=”false”

Create few controls like link button and view the page in browser. You will see that the page is displayed with no tracing information, although its turned ON in web.config but page level tracing has the precedence over application level tracing.

Writing Custom Trace Information

Now on the click event of Link buttons write the custom trace information.

protected void lblwriteMessage_Click(object sender, EventArgs e)
{
	Trace.Write("Custome Message", "Write Link Button clicked");
}
protected void lblwarnMessage_Click(object sender, EventArgs e)
{
	Trace.Warn("Custome Message", "Warn Link Button clicked");
}

when you will click on the WriteLink button, below output will be seen.

ASP.NET Trace
ASP.NET Trace

and when you will click on warn button, the message will be displayed in Red color. so it is suggested to display the the important trace message as a warn.

ASP.NET Trace
ASP.NET Trace

Page.Trace Vs System.Diagnostics.Trace

Create a new class file and write a static function which will write the Trace Message. You will notice that Trace object is not available by default like ASPX page instead you will need to import the package “System.Diagnostics”.

So, there is lot difference in System.Diagnostic.Trace and Page.Trace.

Trace from Diagnostics display the trace information in output window of Visual studio whereas the Trace from page displays the Trace information in ASPX Page.

Integrate System.Diagnostics with ASPX Page (Routing all Trace information to web page)

We will need to add the listener in web.config file to route all the tracing information to the single web page.

To integrate the System.Diagnostics Trace with ASPX page, write below line of code in web.config.

<system.diagnostics>
  <trace>
    <listeners>
       <add name="WebPageTraceListener"
            type="System.Web.WebPageTraceListener, System.Web, Version=2.0.3600.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a"/>
    </listeners>
  </trace>
</system.diagnostics>

The output will look like below image:
ASP.NET Tracing Application Level
trace.axd file

This file contains all the information about the tracing of the application.

To view the trace information just write the file name and you will get page which will look like below snap.

path structure : http://<servername>/webapp/trace.axd

Application Trace in ASP.NET
Application Trace in ASP.NET

Creating Custom Trace Listeners

Database trace listener

.NET has provided us the flexibility of writing our own Trace Listeners in the form of the TraceListener class. Every Trace Listener is inherited from this class; therefore, in order to implement your own Trace Listener, you must inherit your Trace Listener class from this class.

TraceListener class has many virtual and abstract methods; at the very least, each inheritor of this class must implement the Write and WriteLine methods; other important methods are Fail, Close, and Flush. Inheritors are not supposed to implement these methods but it is a good idea to implement these methods. Descriptions of these methods are given in the beginning of the article.

Method Name Result
Fail Outputs the specified text with the Call Stack.
Write Outputs the specified text.
WriteLine Outputs the specified text and a carriage return.
Flush Flushes the output buffer to the target media.
Close Closes the output stream in order to not receive the tracing/debugging output.

Write and WriteLine methods are overloaded; following is a list of all the overloaded version of the Write method:

  • public override void Write(string message)
  • public override void Write(object o)
  • public override void Write(string message, string category)
  • public override void Write(object o, string category)

For this article, I have created a Trace Listener, DatabaseTraceListener, which actually stores trace and debug messages into a database.

add below code in Web.config which stores the connection string information.

<appSettings></pre>
<pre><add key="ConnectionString" value="Data Source=.SQLExpress;Integrated Security=True;User Instance=True;
AttachDBFilename=|DataDirectory|TraceDB.mdf" /></pre>
<pre><add key="MaximumRequests" value="2" /></pre>
<pre></appSettings>

The structure of Table is:

  • TraceDateTime column stores the date and time of the trace message
  • TraceCategory column stores the actual category of the trace message
  • TraceDescription column stores the trace message
  • StackTrace column contains the stack trace
  • DetailedErrorDescription column contains the detailed error message which will be passed in second parameter of the Fail method.
  • create below stored procedure in SQLExpress

    Stored Procedure ASP.NET Tracing
    Now create a class named “DatabaseTraceListener” which inherit the abstract class “TraceListener”. You can check the code snippets in Source code of this article.

    if you want to implement your own Trace Listener, simply derive your listener class from TraceListener class, implement at least the Write and WriteLine methods and you are done.
    In our Example, Flush and Close methods simply save all the cached messages into the database.

    Saving Trace information in File

    We can also save the trace information in log files.

    To save the trace information in File, simply add the following entry in web.config

    <add name="myListener"
    type="System.Diagnostics.TextWriterTraceListener"
    initializeData="TextWriterOutput.log" />
    

    DataGrid Sorting and Paging Example – Part 2

    Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags , with Leave a comment on DataGrid Sorting and Paging Example – Part 2

    For Part 1, visit This URL http://JitendraZaa.com/blog/?p=191

    In this part, i will show that how to Sort the Datagrid Component of ASP.NET.

    To sort Datagrid, we will need DataView and then assign Dataview as datasource to our Grid control.

    We will need to change our code of Part 1.

    Previously, we used DataSet as a Datasource. This time we will use DataTable and get the DataView from DataTable using below line.

    DataView dv = dt.DefaultView; //Where dt id DataTable
    

    So we have created a function, which will return the DataTable as shown below:

    private DataTable GetTableFromDataBase()
    {
    SqlConnection con = null;
    SqlDataAdapter adp = null;
    DataTable dt = new DataTable();
    try
    {
    con = new SqlConnection(conString);
    con.Open();
    adp = new SqlDataAdapter("Select * from Employee",con);
    adp.Fill(dt);
    return dt;
    }
    catch (CustomException ex)
    {
    ex.logException();
    }finally{
    con.Close();
    }
    return null;
    }
    

    we will need to create the function on Sortcommand of the DataGrid.

    The format for sorting the grid is like:

    SortExpression+”asc”

    OR

    SortExpression+”desc”

    Below is the code snap used for the sorting:

    protected void grdEmp_Sort(object source, DataGridSortCommandEventArgs e)
    {
    DataTable dt = GetTableFromDataBase();
    DataView dv = dt.DefaultView;
    string dir = string.Empty;
    if (e.SortExpression.Length > 0)
    {
    if (Session["OldSortDir"] == null)
    {
    Session["OldSortDir"] = e.SortExpression;
    }
    else
    {
    string oldSortExp = Session["OldSortDir"].ToString();
    if (oldSortExp == "asc")
    {
    dir = "desc";
    Session["OldSortDir"] = "desc";
    }
    else
    {
    dir = "asc";
    Session["OldSortDir"] = "asc";
    }
    }
    dv.Sort = e.SortExpression+"  "+dir;
    }
    grdEmp.DataSource = dv;
    grdEmp.DataBind();
    }
    

    The code for the Pagination is written below. Consider Page Size as 3.

    protected void grdEmp_Paging(object source,DataGridPageChangedEventArgs p)
    {
    grdEmp.CurrentPageIndex = p.NewPageIndex;
    BindTable();
    }
    

    Download Source code