Labels

Showing posts with label ASP.Net - Tips-Tricks. Show all posts
Showing posts with label ASP.Net - Tips-Tricks. Show all posts

Friday, January 18, 2008

DefaultButton and DefaultFocus in Master-Content Page

Default Focus, Buttons and Validation Errors with ASP.NET 2.0

One of the common requests with ASP.NET 1.1 today is to have better control over what happens when a user in a browser hits the enter key without having a button or post-back control selected.

ASP.NET 2.0 makes this easier by supporting the concept of a "default button" that can be indicated on either a <form> or <asp:panel> container control. If no button is selected at the time the enter key is selected, the defaultbutton property will drive the appropriate post-back to the server and route the message to the control you want.

<html>
<body>

<form defaultfocus=“textbox2” defaultbutton=“button1” runat=“server”>

<asp:textbox id=“textbox1” runat=“server”/>
<asp:textbox id=“textbox2” runat=“server”/>

<asp:button id=“button1” text=“Same Page” runat=“server”/>

<asp:panel defaultbutton=“button2” runat=“server”>

<asp:textbox id=“foo” runat=“server”/>

<asp:button id=“button2” runat=“server”/>

</asp:panel>

</form>
</body>
</html>

· Here if the enter key is selected the first time the page is loaded, "button1" will be the button that receives the post-back event.

· If the enter key is hit while the user has their cursor focus within the "foo" textbox (contained wtihin the <asp:panel>), then "button2" will be the button that receives the post-back event.

There is a catch in this feature, when the page is using Master Page. In this case, below would be required to handle the situation.

protected void Page_Load(object sender, EventArgs e)

{

Page.Form.DefaultButton = Button2.UniqueID;

}

protected void Page_PreRender(object sender, EventArgs e)

{

Page.SetFocus(TextBox2);

}

Thanks & Regards,

Arun Manglick || Tech Lead

Tuesday, August 28, 2007

Server Side vs Client Side Comments

One common question people ask is what the difference is between using client-side HTML comments and server-side comments.

The key difference is that with client-side comments

· It is the browser which is ignoring the content within them.

· Code/controls within client-side comments will still be executed on the server and sent down to the browser.

· As such, if there is a server error caused within them it will block running the page.

With server-side comments,

  • The ASP.NET compiler ignores everything within these blocks at parse/compile time, and removes the content completely when assembling the page (like its contents weren’t there at all).
  • Consequently, any errors caused by mal-formed controls or issues with inline code or data-binding expressions within them will be ignored.
  • The page is also just as fast with controls/code within server-side comments as if there were no controls/code on the page at all (there is no runtime performance overhead to them).

Thanks & Regards,

Arun Manglick || Tech Lead

Friday, August 17, 2007

Response.ContentType

Response.ContentType

The ContentType property specifies the HTTP content type for the response. If no ContentType is specified, the default is text/HTML.

Few more are:

<% Response.ContentType = "text/HTML" %>

<% Response.ContentType = "image/GIF" %>

<% Response.ContentType = "image/JPEG" %>

<% Response.ContentType = "text/plain" %>

<% Response.ContentType = "image/JPEG" %>

<% Response.ContentType = "audio/MPEG" %>

<% Response.ContentType = "application/x-cdf" %> [Channel Definition Format]

ContentType

A string describing the content type. This string is usually formatted as type/subtype.

Type : is the general content category, and

Subtype: is the specific content type.

For a full list of supported content types, see your Web browser documentation or the current HTTP 1.1 specification located at http://www.w3.org/Protocols/Specs.html and search for "content-type".

Thanks & Regards,

Arun Manglick || Tech Lead

Thursday, July 5, 2007

Problem Solving for SSL:

------------------------------

- To run a page on https, we need to explicitly request the page uisng https.

- To force a page/folder to execute in secure mode do as:

            - Right Click either WebSite/Folder/PAge

            - Directory Securoty Tab

            - Secure Communications

  Once done, IIS won't display the page if its is been requested without https.

 

- Programmatically, we can determine it as:

            If Request.IsSecureConnection Then

                        ----

            else

                        -----

            End if

 

 

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258

 

DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.

Small Issues & Solutions possibly

 

Other Issues

------------------------

 

  1. If we add reference to the system dll [Shared DLLs  e.g System.Window..Forms. Oracle.daTaAccess etc ] in our Web -Proejct, then it does below.
    1. Makes an entry into Web.config, but
    2. Do not copy the referred DLL into bin. That is, these system dlls are still referred from GAC.

 

  1. But When we do this operation in Class Library projects then it does below:
    1. Adds those DLLs into an virtual folder [named as ‘Reference’] as it has no Web.config.
      1. Here the ‘localcopy’ is set to ‘false’, i.e It refers them from the shared location [GAC].
    2. Do not add them in the bin folder.

 

  1. If we add reference to other DLLs, which are not placed in GAC [ Hence not considered as shared DLLs] [ Like Crystal DLL or AJAX control Tool kit DLLs], then it does two things :

 

    1. Makes an entry in  web.config and
    2. Also  makes a local copy in the bin folder as well.

 

  1. But When we do this operation in Class Library projects, then it behaves same as when we refer shared DLLs. i.e

 

    1. Adds those DLLs into an virtual folder [named as ‘Reference’] as it has no Web.config.
      1. Here the ‘localcopy’ is set to ‘true,
    2. Also adds them in the bin folder.

 

 

Note: In case of Non-Shared DLLs, they are either kept locally in the Web-Application’s bin folder [In Web Project] or placed in virtual folder [named as ‘Reference’] with ‘localcopy’ is set to ‘true’. So now even if ur computer has upgraded the new version of dlls, it won't affect ur application unless u remove the reference and re-refer it.

 

 

  1. [Noticed in Tyrelink] :: We need to give write access to the folders if our web application is writing ito it. e.g Logfiles folder in Tyrelink.

 

  1. If ur Web- Solution has Class-Library project [BL] and Web Application then we are required to add the reference of the BL only once. After that as an when we compile the BL, the reference in Web is automatically refreshed. [Read in .Net 2.0 Book].

 

  1. ‘this’ in JS denotes page, rather than object that raised the event.

 

  1. Note:

If u need a hidden button or hidden text box then instead of getting into the visibility properties of the controls, better solution is keep them in div as : <div style="display:none"> ........</div>

 

 

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice - Bridgestone - Tyre Link || Persistent Systems

 

DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.

Problem- Dropdown requires a hidden click if it has a JS validation attahced

Note : Below problem is both in AJAX & Non-AJAX

 

Let say you have a drop down. You have a JS attached with it.

 

// ------------------------------------------------------------------------------------------------------------------------

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" CausesValidation="True" onchange="return Validate();" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">

            <asp:ListItem>aa</asp:ListItem>

            <asp:ListItem>bb</asp:ListItem>

            <asp:ListItem>cc</asp:ListItem>

        </asp:DropDownList>

       

 <asp:Button ID="Button1" runat="server" Text="" OnClick="Button1_Click" Visible="True" />  // Will be hidden button

// ------------------------------------------------------------------------------------------------------------------------

 

// ------------------------------------------------------------------------------------------------------------------------

<script  type="text/javascript">

 

              function Validate()

    {

 

       num = 6;  // Here, could be any compelx logic.

       if(num > 5)

            return true; 

     else

        return false;

    }

 

</script>

// ------------------------------------------------------------------------------------------------------------------------

 

 

What is wrong:

 

            When you change some selection in dropdown, then JavaScript fires and returns ‘ true’. Now though it returns ‘true’ the Server side event does not fires.

            Hence you need to change the script as below.

 

              function Validate()

    {

      num = 6;  // Here, could be any compelx logic.

       if(num > 5)

            {

         // return true;  // Comment it.

 

        var hiddenButton=document.getElementById('<%= Button1.ClientID %>');

        hiddenButton.click();

}

     else

        return false;

    }

 

</script>

 

Solution Required:

 

            Need some good Solution. Please help.

 

 

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258

 

DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.

Problem - Page_ClientValidate() & Drop Down

Page_ClientValidate()) function gives error only with drop down and not wit button when any link outside the page (e.g From Master Page)  is clicked.

 

function Validate()

    { 

       if(Page_ClientValidate())

       {

           if(document.getElementById('dropDownListLanguage').selectedIndex <= 0)

           {

                return false;

           }

           else

           {

                return true;

           }

       }

    }

 

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258

 

DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.

Wednesday, July 4, 2007

FW: How to Register User Controls and Custom Controls in Web.config

 

 

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258

 

From: Arun Manglick [mailto:arun_manglick@persistent.co.in]
Sent: Wednesday, July 04, 2007 6:29 PM
To: 'arunmanglick.post@blogger.com'
Subject: How to Register User Controls and Custom Controls in Web.config

 

Problem:

In previous versions of ASP.NET , to use the custom server controls and user controls on a page, <%@ Register %> directive is used at the top of pages like so:

<%@ Register TagPrefix="ucl" TagName="header" Src="Controls/Header.ascx" %>
<%@ Register TagPrefix="ucl" TagName="footer" Src="Controls/Footer.ascx" %>
<%@ Register TagPrefix="ControlVendor" Assembly="ControlVendor" %>

Once registered these controls can be used anywhere on the page by using the tagprefix and tagnames configured.


<html>
<body>
    <form id="form1" runat="server">
        <ucl:header ID="MyHeader" runat="server" />
    </form>
</body>
</html>

This works fine, but can be a pain to manage when you want to have controls used across lots of pages within your site (especially if you ever move your .ascx files and need to update all of the registration declarations.

Solution:

ASP.NET 2.0 makes control declarations much cleaner and easier to manage. Instead of duplicating them on all your pages, just declare them once within the new pages->controls section with the web.config file of your application:

<?xml version="1.0"?>

<configuration>

  <system.web>
    
    <pages>
      <controls>
        <add tagPrefix="ucl" src="~/Controls/Header.ascx" tagName="header"/>
        <add tagPrefix="ucl" src="~/Controls/Footer.ascx" tagName="footer"/>
        <add tagPrefix="ControlVendor" assembly="ControlVendorAssembly"/>
      </controls>
    </pages>

  </system.web>

</configuration>

Once registered the controls within the web.config file, can then be used similar to above.

<html>
<body>
    <form id="form1" runat="server">
        <ucl:header ID="MyHeader" runat="server" />
    </form>
</body>
</html>

Hope this helps,

 

 

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258

 

DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.

Tuesday, June 26, 2007

Microsoft Guidelines to create a good ASP.NET application - Ver 2

Hi,

Following is the checklist to be followed for good ASP.NET application recommended by Microsoft:

Source:

http://msdn2.microsoft.com/en-us/library/ms998530.aspx

Design Considerations

Check

Description


Consider security and performance.


Partition your application logically.


Evaluate affinity.


Reduce round trips.


Avoid blocking on long-running tasks.


Use caching.


Avoid unnecessary exceptions.


Threading

Check

Description


Tune the thread pool by using the formula to reduce contention.


Consider minIoThreads and minWorkerThreads for burst load.


Do not create threads on a per-request basis.


Avoid blocking threads.


Avoid asynchronous calls unless you have additional parallel work.


Resource Management

Check

Description


Pool resources.


Explicitly call Close or Dispose on resources you open.


Do not cache or block on pooled resources.


Know your application allocation pattern.


Obtain resources late and release them early.


Avoid per-request impersonation.


Pages

Check

Description


Trim your page size.


Enable buffering.


Use Page.IsPostBack to minimize redundant processing.


Partition page content to improve caching efficiency and reduce rendering.


Ensure pages are batch compiled.


Ensure debug is set to false.


Optimize expensive loops.


Consider using Server.Transfer instead of Response.Redirect.


Use client-side validation.


Server Controls

Check

Description


Identify the use of view state in your server controls.


Use server controls where appropriate.


Avoid creating deep hierarchies of controls.


Data Binding

Check

Description


Avoid using Page.DataBind.


Minimize calls to DataBinder.Eval.


Caching

Check

Description


Separate dynamic data from static data in your pages.


Configure the memory limit.


Cache the right data.


Refresh your cache appropriately.


Cache the appropriate form of data.


Use output caching to cache relatively static pages.


Choose the right cache location.


Use VaryBy attributes for selective caching.


Use kernel caching on Microsoft® Windows Server™ 2003.


State Management

Check

Description


Store simple state on the client where possible.


Consider serialization costs.


Application State

Check

Description


Use static properties instead of the Application object to store application state.


Use application state to share static, read-only data.


Do not store single-threaded apartment (STA) COM objects in application state.


Session State

Check

Description


Prefer basic types to reduce serialization costs.


Disable session state if you do not use it.


Avoid storing STA COM objects in session state.


Use the ReadOnly attribute when you can.


View State

Check

Description


Disable view state if you do not need it.


Minimize the number of objects you store in view state.


Determine the size of your view state.


HTTP Modules

Check

Description


Avoid long-running and blocking calls in pipeline code.


Consider asynchronous events.


String Management

Check

Description


Use Response.Write for formatting output.


Use StringBuilder for temporary buffers.


Use HtmlTextWriter when building custom controls.


Exception Management

Check

Description


Implement a Global.asax error handler.


Monitor application exceptions.


Use try/finally on disposable resources.


Write code that avoids exceptions.


Set timeouts aggressively.


COM Interop

Check

Description


Use ASPCOMPAT to call STA COM objects.


Avoid storing COM objects in session state or application state.


Avoid storing STA components in session state.


Do not create STA components in a page constructor.


Supplement classic ASP Server.CreateObject with early binding.


Data Access

Check

Description


Use paging for large result sets.


Use a DataReader for fast and efficient data binding.


Prevent users from requesting too much data.


Consider caching data.


Security Considerations

Check

Description


Constrain unwanted Web server traffic.


Turn off authentication for anonymous access.


Validate user input on the client.


Avoid per-request impersonation.


Avoid caching sensitive data.


Segregate secure and non-secure content.


Only use Secure Sockets Layer (SSL) for pages that require it.


Use absolute URLs for navigation.


Consider using SSL hardware to offload SSL processing.


Tune SSL timeout to avoid SSL session expiration.


Deployment Considerations

Check

Description


Avoid unnecessary process hops.


Understand the performance implications of a remote middle tier.


Short-circuit the HTTP pipeline.


Configure the memory limit.


Disable tracing and debugging.


Ensure content updates do not cause additional assemblies to be loaded.


Avoid XCOPY under heavy load.


Consider precompiling pages.


Consider Web garden configuration.


Consider using HTTP compression.


Consider using perimeter caching.


Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258