Showing posts with label ASP.NET. Show all posts
Showing posts with label ASP.NET. Show all posts

Thursday, October 20, 2016

PHP vs ASP.NET Comparison

Things that need to observe before finalize between PHP and ASP.NET on any project.

ASP.NET code executes a lot faster compared to PHP. In general most of time of pages rendering time dependent on accessing DB and querying database.

In connecting database ASP.NET is a lot better - in we typically use LINQ which translates our object queries into stored procedures in SQL server database. Also connection to database is persistent, one for one website, there is no need for reconnecting.
PHP, in comparison, can't hold SQL server connection between request, it connect, grab data from DB and destroys, when reconnecting the database is often takes 20-30% of page rendering time.

ASP.NET have two main frameworks designed for it (Web forms and MVC), installed with environment, where in PHP you must get a open-source framework. There is no standard framework in PHP like in ASP.NET.
Since PHP is open source, its popularity differs based on people usage. So every year a new framework will come up for PHP in top list.

Whereas ASP.NET language is so rich, standard library has solutions for very much common problems, for PHP its standard library very open to public and any one can override.

Regarding Costing, PHP, MySQL server, PostgreSQL server, Apache server, and Linux OS are all free and upgrades are also free. 
ASP.NET and IIS are free if you purchase Windows OS. There is a substantial licensing cost for a Microsoft Windows Server, Microsoft SQL Server and future upgrades. For example, Microsoft Server 2008 R2 Standard - 64-bit cost is about approximately $1029 and Microsoft SQL Server 2008 Standard Edition For Small Business cost approximately $1038.

For Hosting, Now a days both hosting of PHP and .NET websites are no different. Both a similar or more over same when compared Windows and Linux environments.
PHP requires LAMP (Linux, Apache, MySQL and PHP) which is popular among hosting companies. ASP.NET requires Windows hosting.

Until a few years ago, Windows hosting used to be significantly more expensive than Linux web hosting. This is hardly true today; you can easily find Windows hosts for almost the same price as Linux web hosts. When we have PaaS, Platform as a Service all hosting provides are offering Pay as you service. Ex: Azure, Amazon WS etc.,

PHP is platform independent and can run on any platform — Linux, Unix, Mac OS X, Windows. is built to run only on Windows platform.

There has been much debate about this subject and most of the debates have been biased and have been tailored to promote one of the programming languages instead of informing the audience.
Scalability and ease of maintenance have nothing to do with whether you select PHP or ASP.NET platform. Web Application scalability and ease of maintenance primarily depend on:

  • Programmers' experience
  • Using the best programming practices
  • Using a solid programming framework
  • Following programming guidelines and standards

In my experience ASP.NET can certainly compete and surpass PHP in terms of raw speed. My personal opinion is that a ASP.NET-MVC compiled web application would run more efficiently/faster than the same project that would be written in PHP.

And this debate goes on and on!!!
Thank you

Friday, February 20, 2015

How to get Cookies reference is getting in ashx file

Here is how you can do it if you set Cookies in different pages. Below code will help you get Cookies in ASHX file

  public void ProcessRequest(HttpContext context)
            context.Response.AddHeader("Pragma", "no-cache");
            context.Response.AddHeader("Cache-Control", "private, no-cache");

            if (context.Request.Cookies["UserID"] != null && 
                context.Request.Cookies["UserID"].Value != null 
                && context.Request.Cookies["UserID"].Value.Trim() != "")
                UserID = Convert.ToInt32(context.Request.Cookies["UserID"].Value);

Hope this helps !!

Tuesday, January 27, 2015

How to: Disable Button after Click while maintaining CausesValidation and an OnClick-Method

Here is how you can do it by adding these two lines in your code behind to prevent multiple clicks on a button.

string strProcessScript = "if (!Page_ClientValidate()){ return false; } else{ this.value='Processing...';this.disabled=true; }";
CheckOutButton.Attributes.Add("onclick", strProcessScript + ClientScript.GetPostBackEventReference(CheckOutButton, "").ToString());

If you have ASP.NET Validation controls in your page, then you might need to do this by adding specific validation group to Page_ClientValidate method.

string strProcessScript = "if (!Page_ClientValidate('PaymentValidationGroup')){ return false; } else{ this.value='Processing...';this.disabled=true; }";
CheckOutButton.Attributes.Add("onclick", strProcessScript + ClientScript.GetPostBackEventReference(CheckOutButton, "").ToString());
Only thing you need to change in ASPX is to add following attribute in ASP Button code UseSubmitBehavior="false"
<asp:Button runat="server" ID="PaymentCheckOutButton" ValidationGroup="PaymentValidationGroup"                                          
Text="Proceed to Checkout" UseSubmitBehavior="false" class="btn btn-primary btn-cons pull-right" OnClick="PaymentCheckOutButton_Click" />
Hope this helps!!

Friday, October 24, 2014

How do you clear temporary files in an ASP.NET website project?

All you need to do is stop IIS from Services, go to c:\Windows\Microsoft.NET\Framework\v4.0.30319\ or respective Framework directory, open the Temporary ASP.NET Files and delete the folders

What happens when we delete these files? Is it safe?

Yes, it's safe to delete these, although it may force a dynamic recompilation of any .NET applications you run on the server.

For background, see the Understanding ASP.NET dynamic compilation article on MSDN.

Monday, March 10, 2014

How to access a div or HTML controls is inside a gridview?

Here is an example of how to access a div inside the TemplateColumn of a Grid:


<asp:TemplateField HeaderText="Pick" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemStyle Width="60px" />
<div id="divpickstatus" runat="server">


protected void gridview_schedule_RowDataBound(object sender, GridViewRowEventArgs e)
if (e.Row.RowType == DataControlRowType.DataRow)
HtmlGenericControl divpickstatus = (HtmlGenericControl)e.Row.FindControl("divpickstatus");
Hope this helps.

Tuesday, January 07, 2014

How to hide Validation controls from JavaScript in .NET?

Here is how you can hide validation summary using the below JavaScript.  Call this in your aspx page. This should do trick for you.

// Hiding all validation contorls  
for (i = 0; i < Page_Validators.length; i++) {
ValidatorEnable(Page_Validators[i], false)

It works in IE and Mozilla. Hope this helps

Thursday, October 24, 2013

How to hide Validation Summary from JavaScript in .NET?

Here is how you can hide validation summary using the below JavaScript.  Call this in your aspx page. This should do trick for you.

function HideValidationSummary(){

if (typeof(Page_ValidationSummaries)!= "undefined"){ //hide the validation summaries
for (sums = 0; sums < Page_ValidationSummaries.length; sums++) {
summary = Page_ValidationSummaries[sums]; = "none";


It works in IE and Mozilla. Hope this helps


Saturday, March 23, 2013

SMTP Server Error: Bad sequence of commands. The server response was: you must authenticate first (#5.5.1)

This error occurs due to lock down of default mail server ( by web hosting companies due to SPAM or what ever other security reasons. But if you use “localhost” or default server “” on your local machine it should not be an issue. But if you have a situation where you need to relay e-mail to a remote mail server that is secured you get this exception.

So you need to handle well using built in classes provided by .NET. This is take care by NetworkCredential Class. This class provides credentials for password-based authentication schemes such as basic, digest, NTLM, and Kerberos authentication.

Here is a fully working quick code sample that you can use to get started on your own SMTP-Authentication supporting e-mail code.

   1: try
   2: {
   3:     SmtpClient smtpclient = new SmtpClient();
   4:     NetworkCredential NetworkCredential = new NetworkCredential(smtpUserName, smtpPassword);
   5:     smtpclient.Credentials = NetworkCredential;
   6:     string MailServer = ConfigurationManager.AppSettings["SMTPServer"].ToString();
   7:     MailMessage objEmail = new MailMessage();
   9:     string FromEmail = ConfigurationManager.AppSettings["ErrorReportEmailFrom"].ToString();
  10:     if (FromEmail.IndexOf(";") > 0)
  11:     {
  12:         FromEmail = FromEmail.Replace(";", ",");
  13:     }
  14:     MailAddress FromAddress = new MailAddress(FromEmail);
  15:     objEmail.From = FromAddress;
  17:     string ToEmail = ConfigurationManager.AppSettings["ErrorReportEmailTo"].ToString();
  18:     if (ToEmail.IndexOf(";") > 0)
  19:     {
  20:         ToEmail = ToEmail.Replace(";", ",");
  21:     }
  22:     objEmail.To.Add(ToEmail);
  24:     string CcEmail = ConfigurationManager.AppSettings["CcEmail"].ToString();
  25:     if (CcEmail.IndexOf(";") > 0)
  26:     {
  27:         CcEmail = CcEmail.Replace(";", ",");
  28:     }
  29:     objEmail.CC.Add(CcEmail);
  31:     string BccEmail = ConfigurationManager.AppSettings["BccEmail"].ToString();
  32:     if (BccEmail.IndexOf(";") > 0)
  33:     {
  34:         BccEmail = BccEmail.Replace(";", ",");
  35:     }
  36:     objEmail.Bcc.Add(BccEmail);
  38:     objEmail.Subject = strSubject;
  39:     try
  40:     {
  41:         objEmail.Body = strBody;
  42:         objEmail.IsBodyHtml = true;
  43:         smtpclient.Host = MailServer;
  44:         smtpclient.Send(objEmail);
  45:     }
  46:     catch (Exception ex)
  47:     {
  48:         throw ex;
  49:     }
  50:     finally
  51:     {
  52:         objEmail.Dispose();
  53:     }
  54: }
  55: catch (Exception ex)
  56: {
  58: }

Enjoy coding!!

Wednesday, February 15, 2012

How to: WebDataGrid paging when there are more pages

QuickPages is a method of paging which will give links to a limited number of pages before and after the current page index.   Below is an example of the Paging behavior which is setup to display 3 quick pages along with a "First" and "Last" quick link.  This setup provides the best user experience for paged records which return more than 8 pages of data.

<ig:Paging PagerAppearance="Both" PagerMode="NumericFirstLast" 
QuickPages="3" PageSize="20"
FirstPageText="First" LastPageText="Last" >

Hope this helps!

Sunday, November 13, 2011

Validators Control to allow only Integers

Here are few different ways you can use native .NET validation controls to validate to allow only integers. We can do it in two ways one by using regular expression and one with compare validators

Method 1: Compare Validator
<asp:TextBox ID="NewMobileTextBox" runat="server" Width="280px" autocomplete="off"
CssClass="signuptxtbox" ></asp:TextBox>
<asp:RequiredFieldValidator ID="NewMobileRequired" runat="server" ControlToValidate="NewMobileTextBox"
CssClass="failureNotification" Display="Dynamic" ErrorMessage="New Mobile is required." ToolTip="New Mobile is required." ValidationGroup="ChangeNewMobileValidationGroup">*</asp:RequiredFieldValidator>
<asp:CompareValidator ID="NewMobileCompare" runat="server" ControlToValidate="NewMobileTextBox" CssClass="failureNotification" Display="Dynamic" Operator="DataTypeCheck" ErrorMessage="Mobile Number should be numeric only." ValidationGroup="ChangeNewMobileValidationGroup" Type="Integer">*</asp:CompareValidator>

Method 2: Regular Expression Validator

<asp:TextBox ID="NewMobileTextBox" runat="server" Width="280px" autocomplete="off"
CssClass="signuptxtbox" ></asp:TextBox><asp:RequiredFieldValidator ID="NewMobileRequired" runat="server" ControlToValidate="NewMobileTextBox"
CssClass="failureNotification" Display="Dynamic" ErrorMessage="New Mobile is required." ToolTip="New Mobile is required." ValidationGroup="ChangeNewMobileValidationGroup">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="mobileRGEX" runat="server"
ControlToValidate="NewMobileTextBox" CssClass="failureNotification"
ErrorMessage="Please Enter Only Numbers" ValidationExpression="^\d+$"

Saturday, September 10, 2011

Convert DateTime values to W3C DateTime format in C#

ConvertDateToW3CTime() function takes a C# DateTime value and converts it to a W3C formatted date/time value.
The function works by first converting the date/time parameter to a UTC (Coordinated Universal Time) value and formatting it. It then appends the UTC offset time to the previously formatted string.

The T placed between the date and time simply indicates that the numbers following it are Time values. The UTC offset can be one 3 states, zero e.g. there is not difference in time between the UTC value and the local value. A zero value is identified by simply appending the letter Z to the end of the formatted datetime value. If the offset time is greater than 0 then it is preceded with a + sign, e.g. 2 hours and 30 minutes over the UTC time would be written as +02:30. If the offset is less than the UTC value then it is preceded with a sign e.g. -01:00.

/// <summary>
/// Converts a datetime value to w3c format
/// </summary>
/// <param name="date"></param>
/// <returns></returns>
public static string ConvertDateToW3CTime(DateTime date)
//Get the utc offset from the date value
var utcOffset = TimeZone.CurrentTimeZone.GetUtcOffset(date);
string w3CTime = date.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss");
//append the offset e.g. z=0, add 1 hour is +01:00
w3CTime += utcOffset == TimeSpan.Zero ? "Z" :
String.Format("{0}{1:00}:{2:00}", (utcOffset > TimeSpan.Zero ? "+" : "-")
, utcOffset.Hours, utcOffset.Minutes);

return w3CTime;

Here is an example, how to use it

//Output 2011-10-17T19:10:48+01:00

Thursday, January 13, 2011

Export GridView to Excel in ASP.NET

Here is the same code to export GridView from C# in ASP.NET

protected void ExportButton_Click(object sender, EventArgs e)
   Response.AddHeader("content-disposition", "attachment;filename=Contacts.xls");
   Response.Charset = String.Empty;
   Response.ContentType = "application/vnd.xls";
   System.IO.StringWriter sw = new System.IO.StringWriter();
   System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
Hope this is useful Just kidding

How to update Web.config dynamically?

I need to update web.config dynamically? So this is what I did, this code below has done the trick for me.

string value = "";
Configuration config = webConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection appsetting = config.GetSection("appSettings");
appsetting.Settings("fromAddress").Value = value;
Make sure to add System.Web.Configuration in the namespace. Have fun Light bulb

Friday, July 30, 2010

How to: List all Query string variables in C#

This is how you can do it in C#, Either of will work for getting Query string values

for (int i = 0; i < Request.QueryString.Count; i++)
    Response.Write(Request.QueryString.Keys[i].ToString()+ ":"+Request.QueryString.Keys[i].ToString()+"<br/>");
foreach (string key in Request.QueryString.Keys)
    Response.Write(key+ ":"+Request.QueryString[key]+"<br/>");

How to: List all Session variables?

This is how we can get list of all session variables using c#.

for (int i = 0; i < Session.Contents.Count; i++)
    Response.Write(Session.Keys[i] + " - " + Session[i] + "<br />");
foreach (string key in Session.Keys)
    Response.Write(key + " - " + Session[key] + "<br />");

Either of them can get you all session details.

Thursday, June 24, 2010

Dynamically Loading Master Pages

Master Pages give you the ability to define a master page layout and look that is used throughout a site to give a consistent look & feel to all pages. Any updates or changes to the look & feel of the site is done in only one place - the Master Page. Something that might be useful is the ability to dynamically load a master page at runtime, for example based on user preferences or to implement a simple skinning ability for a site framework that might host multiple different sites.

The master page can be selected for a page easily at design-time. But assigning a master page at run-time can only be done in the OnPreInit event since the rendering of the page with the master page occurs prior to the Init event. However, in the case where you want to load the master page dynamically, for example from a database entry based on a user's preference or something, you don't want to add code to the OnPreInit event on every page in the site. It is easy enough to add that code to a base page class that you can inherit from for you pages in the site.

public class DynamicPage : System.Web.UI.Page
protected override void OnPreInit(EventArgs e)
string masterfile = getMasterPageFromDatabase();
if (!masterfile.Equals(string.Empty))
base.MasterPageFile = masterfile;

Now, all you have to do is inherit from that class for all the pages in the site. You can just add it into the web.config and all pages will automatically inherit from it. Doesn't matter if it is a page in the project that you have already, or a new page you add later, it will know to inherit from the DynamicPage class. You add the following to the web.config:

<pages pageBaseType="DynamicPage" />
<!-- of system.web items... -->

Friday, June 18, 2010

ASP.NET 4 Breaking Changes

.Net Framework 4.0 comes up with some of major changes as compare to previous versions of .Net Framework 3.5 and 2.0
Following are list of Major Changes in .Net 4.0

  • ControlRenderingCompatabilityVersion Setting in the Web.config File 
  • ClientIDMode Changes 
  • HtmlEncode and UrlEncode Now Encode Single Quotation Marks 
  • ASP.NET Page (.aspx) Parser is Stricter 
  • Browser Definition Files Updated 
  • System.Web.Mobile.dll Removed from Root Web Configuration File 
  • ASP.NET Request Validation 
  • Default Hashing Algorithm Is Now HMACSHA256 
  • Configuration Errors Related to New ASP.NET 4 Root Configuration 
  • ASP.NET 4 Child Applications Fail to Start When Under ASP.NET 2.0 or ASP.NET 3.5 Applications 
  • ASP.NET 4 Web Sites Fail to Start on Computers Where SharePoint Is Installed 
  • The HttpRequest.FilePath Property No Longer Includes PathInfo Values 
  • ASP.NET 2.0 Applications Might Generate HttpException Errors that Reference eurl.axd 
  • Event Handlers Might Not Be Not Raised in a Default Document in IIS 7 or IIS 7.5 Integrated Mode Changes to the ASP.NET Code Access Security (CAS) Implementation 
  • MembershipUser and Other Types in the System.Web.Security Namespace Have Been Moved 
  • Output Caching Changes to Vary * HTTP Header 
  • System.Web.Security Types for Passport are Obsolete 
  • The MenuItem.PopOutImageUrl Property Fails to Render an Image in ASP.NET 4 
  • Menu.StaticPopOutImageUrl and Menu.DynamicPopOutImageUrl Fail to Render Images When Paths Contain Backslashes 

Find detail information of ASP.NET 4 Breaking Changes

Tuesday, May 25, 2010

Disabling Browser Cache In C# and ASP.NET

Disable browser caching seems to revolve around how to make it work in IE, Mozilla and other browsers.

Here is the code that will disable browser cache. I have used this and it worked for me.

//Used for disabling page caching 
// Requires for IE
// Requires for Mozilla

Wednesday, April 07, 2010

GridView Export from ASP.NET

Common method for Exporting gird content 

#region Methods : ExportGridView & PrepareControlForExport
    /// <summary>
    /// Purpose : To Export GridView in Excel format.
    /// </summary>
    /// <param name="strFileName">Execl File name</param>
    /// <param name="gv">Grid View</param>
    /// <param name="isRemove">If false, wont check the remove column</param>
    /// <param name="arrayList">List of columns to hide {1,2,3}</param>
    /// <param name="removeColumn">Column to remove</param>
    public void ExportGridView(string strFileName, GridView gv, bool isRemove, ArrayList arrayList)
            "content-disposition", string.Format("attachment; filename={0}", strFileName));
        HttpContext.Current.Response.ContentType = "application/ms-excel";

        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);

        Table tableExport = new Table();
        // Setting line borders to the exported grid
        tableExport.GridLines = GridLines.Both;

        if (isRemove == false)
            if (gv.HeaderRow != null)
            foreach (GridViewRow row in gv.Rows)
            if (gv.FooterRow != null)

            if (arrayList.Count > 0)
                    if (gv.HeaderRow != null)
                        for (int removeColumn = 0; removeColumn < arrayList.Count; removeColumn++)
                    foreach (GridViewRow row in gv.Rows)
                        for (int removeColumn = 0; removeColumn < arrayList.Count; removeColumn++)
                    if (gv.FooterRow != null)
                        for (int removeColumn = 0; removeColumn < arrayList.Count; removeColumn++)



    /// <summary>
    /// Prepaing the control for export
    /// Customize your controls depening on your logic    ///
    /// </summary>
    /// <param name="control"></param>
    private void PrepareControlForExport(Control control)
        for (int i = 0; i < control.Controls.Count; i++)
            Control current = control.Controls[i];
            if (current is LinkButton)
                if ((current as LinkButton).Style["display"] != "none" && (current as LinkButton).Visible)
                    control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text.Trim()));
            else if (current is ImageButton)
                control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText.Trim()));
            else if (current is HyperLink)
                control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text.Trim()));
            else if (current is DropDownList)
                control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text.Trim()));
            else if (current is CheckBox)
                control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
            else if (current is HtmlAnchor)
                control.Controls.AddAt(i, new LiteralControl((current as HtmlAnchor).InnerText.Trim()));
            else if (current is Label)
                if ((current as Label).Style["display"] != "none" && (current as Label).Visible)
                    control.Controls.AddAt(i, new LiteralControl((current as Label).Text.Trim()));

            if (current.HasControls())
    #endregion Methods : ExportGridView & PrepareControlForExport


Sample code to call code behind

   ArrayList list = new ArrayList();
            DraftsGridView.AllowPaging = false;
            BindDrafts("StartDateTime", ASCENDING);
         // Add list of columns that are to be hidden. If you not need any columns
        //then just send list object without adding any and set the third parameter to false
            common.ExportGridView("Drafts.xls", DraftsGridView, true, list);