Showing posts with label ASPNET. Show all posts
Showing posts with label ASPNET. Show all posts

Sunday, October 6, 2013

Replace HtmlTextWriter before render

If we want to change HTML of control before rendering you can use the following code:
protected override void Render(HtmlTextWriter writer)
{

MemoryStream stream = new MemoryStream();
StreamWriter memWriter = new StreamWriter(stream);
HtmlTextWriter myWriter = new HtmlTextWriter(memWriter);
base.Render(myWriter);
myWriter.Flush();
stream.Position = 0;
using (StreamReader sr = new StreamReader(stream))
{
string renderedHtml = sr.ReadToEnd();
renderedHtml = renderedHtml.Replace("It looks like your browser does not have JavaScript enabled. Please turn on JavaScript and try again.", "");
writer.Write(renderedHtml);
writer.Close();
myWriter.Close();
}
//base.Render(writer);
}

Sunday, December 23, 2012

How to Make ODP.NET 4.0 (64 bit) working on 64 bit machine


When you Install ODP.NET 64 bit and try to use it in Visual Studio 2010 and the project is of type ASP.NET Website. it give the error from the web.config file during compile time.


"Could not load file or assembly 'Oracle.DataAccess, Version=4.112.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342' or one of its dependencies. The system cannot find the file specified"

The best possibility to handle this is to use the x86 version locally with Visual Studio and x64 version on the server with IIS. To do this you have to download both versions - copy one in folder lib\x86 and the other in lib\x64 After this you have to modify the project file(s) - visual studio supports conditional references. Add following section to your project file:


 <PropertyGroup>
     <ReferencesPath Condition=" '$(Platform)' == 'x86' ">..\Lib\x86</ReferencesPath>   
     <ReferencesPath Condition=" '$(Platform)' == 'x64' ">..\Lib\x64</ReferencesPath>     
 </PropertyGroup>


After this reference the odp.net assmebly like this:


  <Reference ... processorArchitecture=$(Platform)">
   <SpecificVersion>False</SpecificVersion>
   <HintPath>$(ReferencesPath)\Oracle.DataAccess.dll</HintPath>          
   <Private>True</Private>
  </Reference>

Tuesday, April 24, 2012

Tips Comment ASPNET Controls

Some times ASPNET Developer do mistake by commenting server controls
as html comment like below:
<!--<aspnet:TextBox runat="server" id="txt"/>

-->

This comment will affect only by rendering tags as commented html, but doesn't affect its server side events and validations. which
will cause many problems. It is displaying sensitive information, it is vulnerable to cross-site scripting,  failure in firing some scripts like script validation, unexpected behaviour of scripts, and render unwanted tags(affect the performance).

To ignore any of the above problems use server side:
<%--<aspnet:TextBox runat="server" id="txt"/>

--%>

Wednesday, May 18, 2011

An ASP.NET HttpModule to set the current culture to the user’s locale

My web application needs to display user information depend on its default culture.


I created an ASP.NET module:





using System;
using System.Globalization;
using System.Threading;
using System.Web;
namespace Gold.Translate
{
public class UserLocaleModule : IHttpModule
{
public void Init(HttpApplication httpApplication)
{
httpApplication.BeginRequest += (sender, eventArgs) =>
{
var app = sender as HttpApplication;
if (app == null)
{
throw new ApplicationException("Sender is null or not an HttpApplication");
}
var request = app.Context.Request;
if (request.UserLanguages == null request.UserLanguages.Length == 0) return;

var language = request.UserLanguages[0];
if (language == null) return;

try
{
Thread.CurrentThread.CurrentCulture = new CultureInfo(language);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(language);
}
catch
{}
};
}

public void Dispose()
{

}
}
}

Configuration in web.config for classic mode:








<httpModules runAllManagedModulesForAllRequests="true">
<add name="UserLocale" type="Gold.Translate.UserLocaleModule, Gold.Translate" />
</httpModules>


Configuration in web.config for integration mode:








<modules runAllManagedModulesForAllRequests="true">
<add name="UserLocale" type="Gold.Translate.UserLocaleModule, Gold.Translate" />
</modules>



Saturday, April 19, 2008

Tips to Improve ASP.net Application Performance

  1. Disable Session StateDisable Session State
    if you're not going to use it. By default it's on. You can actually turn this off for specific pages, instead of for every page:
    <%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="WebApplication1.WebForm1" EnableSessionState="false" %>
    <%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="WebApplication1.WebForm1" EnableSessionState="false" %>

    You can also disable it across the application in the web.config by setting the mode value to Off.
  2. Output Buffering
    Take advantage of this great feature. Basically batch all of your work on the server, and then run a Response.Flush method to output the data. This avoids chatty back and forth with the server.<%response.buffer=true%>

    &lt%response.buffer=true%>

    Then use:

    <%response.flush=true%>
  3. Avoid Server-Side Validation
    Try to avoid server-side validation, use client-side instead. Server-Side will just consume valuable resources on your servers, and cause more chat back and forth.
  4. Repeater Control Good, DataList, DataGrid, and DataView controls
    BadAsp.net is a great platform, unfortunately a lot of the controls that were developed are heavy in html, and create not the greatest scaleable html from a performance standpoint. ASP.net repeater control is awesome! Use it! You might write more code, but you will thank me in the long run!
  5. Take advantage of HttpResponse.IsClientConnected before performing a large
    operation:
    if (Response.IsClientConnected)
    {
    // If still connected, redirect
    // to another page.
    Response.Redirect("Page2CS.aspx", false);
    }
    What is wrong with Response.Redirect? More
  6. Use HTTPServerUtility.Transfer instead of Response.Redirect
    Redirect's are also very chatty. They should only be used when you are transferring people to another physical web server. For any transfers within your server, use .transfer! You will save a lot of needless HTTP requests.
  7. Always check Page.IsValid when using Validator Controls
    So you've dropped on some validator controls, and you think your good to go because ASP.net does everything for you! Right? Wrong! All that happens if bad data is received is the IsValid flag is set to false. So make sure you check Page.IsValid before processing your forms!
  8. Deploy with Release Build
    Make sure you use Release Build mode and not Debug Build when you deploy your site to production. If you think this doesn't matter, think again. By running in debug mode, you are creating PDB's and cranking up the timeout. Deploy Release mode and you will see the speed improvements.
  9. Turn off Tracing
    Tracing is awesome, however have you remembered to turn it off? If not, make sure you edit your web.config and turn it off! It will add a lot of overhead to your application that is not needed in a production environment.

    <configuration>
    <system.web>
    <trace enabled="false" pageOutput="false" />
    <trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true"/>
    <compilation debug="false" />
    </system.web>
    </configuration>
  10. Page.IsPostBack is your friend
    Make sure you don't execute code needlessly.
    I don't know how many web developers forget about checking IsPostBack! It seems like such a basic thing to me! Needless processing!
  11. Avoid Exceptions
    Avoid throwing exceptions, and handling useless exceptions. Exceptions are probably one of the heaviest resource hogs and causes of slowdowns you will ever see in web applications, as well as windows applications. Write your code so they don't happen! Don't code by exception!
  12. Caching is Possibly the number one tip!
    Use Quick Page Caching and the ASP.net Cache API! Lots to learn, its not as simple as you might think. There is a lot of strategy involved here. When do you cache? what do you cache?
  13. Create Per-Request Cache
    Use HTTPContect.Items to add single page load to create a per-request cache.
  14. StringBuilder
    StringBuilder. Append is faster than String + String. However in order to use StringBuilder, you must
    new StringBuilder()
    Therefore it is not something you want to use if you don't have large strings. If you are concatenating less than 3 times, then stick with String + String. You can also try String.Concat
  15. Turn Off ViewState
    If you are not using form postback, turn off viewsate, by default, controls will turn on viewsate and slow your site.

    public ShowOrdersTablePage()
    {
    this.Init += new EventHandler(Page_Init);
    }

    private void Page_Init(object sender, System.EventArgs e)
    {
    this.EnableViewState = false;
    }
  16. Use Paging
    Take advantage of paging's simplicity in .net. Only show small subsets of data at a time, allowing the page to load faster. Just be careful when you mix in caching. How many times do you hit the page 2, or page 3 button? Hardly ever right! So don't cache all the data in the grid! Think of it this way: How big would the first search result page be for "music" on Google if they cached all the pages from 1 to goggle ;)
  17. Use the AppOffline.htm when updating binaries
    I hate the generic asp.net error messages! If I never had to see them again I would be so happy. Make sure your users never see them! Use the AppOffline.htm file!
  18. Use ControlState and not ViewState for Controls
    If you followed the last tip, you are probably freaking out at the though of your controls not working. Simply use Control State. Microsoft has an excellent example of using ControlState here
  19. Use the Finally Method
    If you have opened any connections to the database, or files, etc, make sure that you close them at the end! The Finally block is really the best place to do so, as it is the only block of code that will surely execute.
  20. Option Strict and Option Explicit
    This is an oldy, and not so much a strictly ASP.net tip, but a .net tip in general. Make sure you turn BOTH on. you should never trust .net or any compiler to perform conversions for you. That's just shady programming, and low quality code anyway. If you have never turned both on, go turn them on right now and try and compile. Fix all your errors.