Showing posts with label ASP.NET 2.0. Show all posts
Showing posts with label ASP.NET 2.0. 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 asp.net 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.

ASP.net 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

Tuesday, January 27, 2015

How to access ViewState of one page in another page in Asp.Net?

You can't access ViewState of one page from another page directly. If you want to access a particular ViewState value then you can pass the value in Context collection and then access the value in other page.

In Page 1:

Context.Items.Add("employee" ,ViewState["employee"].ToString());


In Page 2:


string employeeName = Context.Items["employee"].ToString();

Hope this helps!

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.

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;
}
base.OnPreInit(e);
}
}


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:



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

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)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader(
            "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)
            {
                this.PrepareControlForExport(gv.HeaderRow);
                tableExport.Rows.Add(gv.HeaderRow);
            }
            foreach (GridViewRow row in gv.Rows)
            {
                this.PrepareControlForExport(row);
                tableExport.Rows.Add(row);
            }
            if (gv.FooterRow != null)
            {
                this.PrepareControlForExport(gv.FooterRow);
                tableExport.Rows.Add(gv.FooterRow);
            }

        }
        else
        {
            if (arrayList.Count > 0)
            {
                    if (gv.HeaderRow != null)
                    {
                        this.PrepareControlForExport(gv.HeaderRow);
                        tableExport.Rows.Add(gv.HeaderRow);
                        for (int removeColumn = 0; removeColumn < arrayList.Count; removeColumn++)
                        {
                            gv.HeaderRow.Cells.Remove(gv.HeaderRow.Cells[Int32.Parse(arrayList[removeColumn].ToString())]);
                        }
                    }
                    foreach (GridViewRow row in gv.Rows)
                    {
                        this.PrepareControlForExport(row);
                        for (int removeColumn = 0; removeColumn < arrayList.Count; removeColumn++)
                        {
                            row.Cells.Remove(row.Cells[Int32.Parse(arrayList[removeColumn].ToString())]);
                        }
                        tableExport.Rows.Add(row);
                    }
                    if (gv.FooterRow != null)
                    {
                        this.PrepareControlForExport(gv.FooterRow);
                        tableExport.Rows.Add(gv.FooterRow);
                        for (int removeColumn = 0; removeColumn < arrayList.Count; removeColumn++)
                        {
                            gv.FooterRow.Cells.Remove(gv.FooterRow.Cells[Int32.Parse(arrayList[removeColumn].ToString())]);
                        }
                    }
            }
        }

        tableExport.RenderControl(htw);
        HttpContext.Current.Response.Write(sw.ToString().Trim());
        HttpContext.Current.Response.End();

    }

    /// <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)
            {
                control.Controls.Remove(current);
                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.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText.Trim()));
            }
            else if (current is HyperLink)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text.Trim()));
            }
            else if (current is DropDownList)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text.Trim()));
            }
            else if (current is CheckBox)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
            }
            else if (current is HtmlAnchor)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as HtmlAnchor).InnerText.Trim()));
            }
            else if (current is Label)
            {
                control.Controls.Remove(current);
                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())
            {
                this.PrepareControlForExport(current);
            }
        }
    }
    #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
            list.Add(3);
            common.ExportGridView("Drafts.xls", DraftsGridView, true, list);

Thursday, February 25, 2010

Get ASP.NET Menu work on Chrome, Safari and Opera

I have done some research on this, i found couple of interesting solutions. Actually the are cracks to get Menu working

Solution 1:

// For Cross Browser Compatibility (Safari/Chrome) 
       if (Request.UserAgent.IndexOf("AppleWebKit") > 0) 
       { 
           Request.Browser.Adapters.Clear(); 
       }


I have added this code in master page. I Worked when there is no master page. But when there is a master page its not working for the first time so found below code which works with master page.



Solution 2:



protected override void AddedControl(Control control, int index) 
  { 
      if (Request.ServerVariables["http_user_agent"].IndexOf("Safari", StringComparison.CurrentCultureIgnoreCase) != -1) 
      { 
          this.Page.ClientTarget = "uplevel"; 
      } 
      base.AddedControl(control, index); 
  }


The reason i added it in the AddedControl method was so that i didn't have to use a basepage or parent class that every single aspx file had to inherit. And its the only method that i found to run before the Page_PreInit. Hope it works for you too!

Thursday, February 18, 2010

Potentially dangerous Request.Form value was detected from the client : ValidateRequest

This error is caused because the .NET framework detected HTML in an input control (e.g. TextBox). I've highlighted 3 possible ways to get round the issue, all with their advantages and disadvantages:

1. Add the following to the existing Page directive on the relevant pages.

<%@ Page Language="C#" MasterPageFile="~/Master.master" ValidateRequest="false" AutoEventWireup="true" CodeFile="Default.aspx.cs"
    Inherits="_Default" %>

2. Add the following to the Web.config within the <system.web> section (globally disable request validation). This will allow users to enter HTML into controls which could be harmful or result in undesirable consequences.

<system.web>

<pages validateRequest="false" />

</system.web>

3. Unless you need users to be able to enter HTML into a form, make sure all HTML displayed in controls is encoded.

lblTextBox.Text = HttpUtility.HtmlEncode( lblTextBox.Text );

Tuesday, September 15, 2009

File Monitoring in .NET

File monitoring applications can be easily developed in .NET using the FileSystemWatcher class. This class listens to changes in files system and raises events whenever changes happen. This article explains how to monitor changes in files and subdirectories of a directory using the FileSystemWatcher class.
The FileSystemWatcher is available within the System.IO namespace. We need to include the System.IO namespace for accessing the FileSystemWatcher class. In order to specify the folder to monitor we have to set the Path property of the FileSystemWatcher as shown below:

FileSystemWatcher fsw = new FileSystemWatcher();
fsw.Path = "c:\\fileWatcher";
If you want to monitor changes to a specific file then the Filter property should be used along with the Path property. The Filter property should be set to file name and the Path property should be set to the path of the folder as shown below
fsw.Path = "c:\\fileWatcher ";
fsw.Filter = "TestWatchFile.txt";
Wild card characters can also be used to specify set of files as shown below
fsw.Filter = "*.txt";
The FileSystemWatcher to begin monitoring we have to set the EnableRaisingEvents property to true
fsw.EnableRaisingEvents = true;

As mentioned before the FileSystemWatcher raises events whenever changes like creation, deletion etc happens to the specific folder or file. The events that are raised by FileSystemWatcher are Changed, Created, Deleted, Error and Renamed.

We need to write appropriate event handlers to handle these events. The FileSystemEventHandler has an argument named FileSystemEventArgs, which provides useful event data. The data provided by the FileSystemEventArgs are ChangeType which gives the type of change that occurred and Path which gives the full path of the affected file or folder.

A sample Changed event handler is given below
fsw.Changed += new FileSystemEventHandler(fsw_changed);
fsw.Deleted += new FileSystemEventHandler(fsw_changed);
fsw.Created += new FileSystemEventHandler(fsw_changed);
private void fsw_changed(object Sender,FileSystemEventArgs e)
{
MessageBox.Show("The file" + e.FullPath+ " was " + e.ChangeType.ToString() + " on " + System.DateTime.Now.ToString());
}

FileSystemObject class can be used to monitor files or folders by setting appropriate properties and handling the events raised by the class.

Monday, July 27, 2009

What is AutoEventWireup?

ASP.NET page framework also supports an automatic way to associate page events and methods. If the AutoEventWireup attribute of the Page directive is set to true (or if it is missing, since by default it is true), the page framework calls page events automatically, specifically the Page_Init and Page_Load methods. In that case, no explicit Handles clause or delegate is needed.

The disadvantage of the AutoEventWireup attribute is that it requires that the page event handlers have specific, predictable names. This limits your flexibility in how you name your event handlers. Therefore, in Visual Studio, the AutoEventWireup attribute is set to false by default and the designer generates explicit code to bind page events to methods.

If you do set AutoEventWireup to true, Visual Studio will generate code to bind the events and the page framework will automatically call events based on their names. This can result in the same event code being called twice when the page runs. As a consequence, you should always leave AutoEventWireup set to false when working in Visual Studio.

For more information Click here

Wednesday, July 15, 2009

asp:Menu Server Control - Cross Browser Compatibility (Safari/Chrome)

 

Cross browser compatibility is upsetting while working with asp:Menu Server Control, and It was not rendering/working well with Safari and Chrome.

After bit of googling... :-) and found a solution for this.

Approach 1:

I have added below small piece of code snippet in my MasterPage's Page_Load event

        if (Request.UserAgent.IndexOf("AppleWebKit") > 0)
        {
            Request.Browser.Adapters.Clear();
        }

This will tell asp.net not to use an adapter when rendering the menu control. This will work for both Safari and chrome as well because they both use webkit which is how asp.net identifies.

Approach 2:

You can force the menu to work by overwrite the Page_PreInit method on the page and telling the page that the client target is a modern “uplevel” browser:-

protected void Page_PreInit(object sender, EventArgs e)
{
if (Page.Request.ServerVariables["http_user_agent"].ToLower().Contains("safari"))
{
Page.ClientTarget = "uplevel";
}
}

Unfortunately, you can't just add the fix to your Master Page, it doesn't contain a PreInit method as it's a web control not a web page.

Please note that you have to do this in the page class file, and not in the master page class file. Obviously this means you have to do it for every page – which is not ideal.

Thursday, January 03, 2008

Accessing Master Page Properties from a content page

Accessing a property on a MasterPage from the content page. One merely has to check the namespace and the class name of the masterpage, which can be found in the code behind file. Just cast the Content Page’s Master as the class of the masterpage file which it uses, and then access the value.
One way of doing this in the content page,

int valueNeeded = ((MyNameSpace.MyMasterPageClassName)Master).MyProperty;

Or you can do this by doing like this in ContentPage.aspx page
<%@ MasterType VirtualPath="~/MasterPage.master" %>
Just below the Page directive and then you can access the proeprty in codebehind in content file as as:

int valueNeeded = Master.MyProperty;

Using these methods you can access a property of a masterpage file.

Wednesday, September 12, 2007

Building a Custom Database-Driven Site Map Provider

Building a Custom Database Driven Site Map Provider: Scott Mitchell has written a great article on how to implement your own site map provider for ASP.NET that is populated from a database (instead of statically from an XML file).

Thursday, July 12, 2007

Programmatically accessing Tracing info in Asp.Net 2.0

For enabling Tracing we normally Tweak the config file right....

But in asp.net 2.0 you can do a bit more...

void Page_Load (object sender, EventArgs e)
{
Trace.TraceFinished +=
new TraceContextEventHandler (TraceHasFinished);
}

void TraceHasFinished (object sender, TraceContextEventArgs e)
{
foreach (TraceContextRecord traceContextRecord in e.TraceRecords)
{
Response.Write (traceContextRecord.Category + "
");
Response.Write (traceContextRecord.Message + "
");
//..... Do your bits .......
//...Write as XML....
//....Or Write to Database....Up to you....
}
}

How cool is that! you have now programmatic access. Just register to the event TraceFinished of the TraceContext class and loop through the e.TraceRecords.