Tuesday, December 28, 2010

Error retrieving CRM information in a Silverlight (System.Security.SecurityException: Security error)

01. To Solve : use a crossdomain.xml file to allow cross-domain access
02.create crossdomain.xml file to CRM hosted folder in IIS (Root)

<?xml version="1.0" encoding="utf-8" ?>
<allow-from http-request-headers="*">
<domain uri="*"/>
<resource include-subpaths="true" path="/"/>

Wednesday, November 10, 2010

Get Parent Form Details Using Java Script In CRM 2011(Sub Grid Form)

01.Get Crm Service
function init() {

// Set Global Variables
var serverUrl = Xrm.Page.context.getServerUrl();
ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
// var Id = Xrm.Page.data.entity.getId();

02.Pass Parent Id (GuID) in to Service
function retrieveAccountRecord(GuId parentID ) {

//Set Request
var retrieveAccountReq = new XMLHttpRequest();
var path = ODataPath + "/mship_subscriptionmatrixSet(guid'" + parentID + "')";
retrieveAccountReq.open("GET", path, true);
retrieveAccountReq.setRequestHeader("Accept", "application/json");
retrieveAccountReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");

retrieveAccountReq.onreadystatechange = function () {


function retrieveAccountReqCallBack(retrieveAccountReq) {
if (retrieveAccountReq.readyState == 4 /* complete */) {
if (retrieveAccountReq.status == 200) {
var retrievedAccount = JSON.parse(retrieveAccountReq.responseText).d;
var testOb = retrievedAccount.new_name; //



03.you can retrieve all values in retrievedAccount in Parent.

////////Apply this in Child form Load Event.....

///////To get Parent Id in Sub Grid//////////////

If you want to retrieve parent Data in Sub Grid form you can also use above.
To get parent record guid
01.Get server Url and get Created Form id parameter Value like Bellow.
var parentID = GetUrlParameter(); //Get Parent Page Id
parentID = parentID.substring(3, parentID.length - 3);

function GetUrlParameter() {
var id = "";
var name = "_CreateFromId";

name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);

if (results == null) {

} else {
id = results[1];
return id;

Monday, November 1, 2010

Create Many to one relationship with Adding lookup in CRM entity(Account / Contract)

Create new lookup attribute

While most types of new attributes are created in the Attributes area of an entity, lookup attributes are created automatically when you create a relationship between two entities.

There are two types of relationships you can create: many-to-one and one-to-many. Because many accounts can be associated with one Contract, you’ll create a many-to-one relationship from the Account entity to the Contract entity. This is the most commonly used relationship type for a lookup because typically any number of records in the entity to which you are adding the lookup can be associated with one record in the custom entity.

1.In Microsoft CRM Dynamics CRM , click Settings, click Customization, click Customize Entities, double-click Account, and then click Relationships.

2.On the Actions toolbar, click New Many-to-1 Relationship.

3.In the Relationship: New dialog box, in the Primary Entity box, select Contract.

4.In the Display Name box, type Contract. Though this is the display name for the relationship, it is also the display name of the new lookup attribute. The Type field is set to lookup.

5.If you want this attribute to be Business Required or Recommended, select the appropriate setting in the Requirement Level box.

6.In the Relationship Behavior section, in the Type of Behavior box, select Referential.

7.Click Save and Close. This leaves the Entity: Account form open. Keep this form open, because you will use it in the next procedure.
Top of pageTop of page
Add your new lookup attribute to a form

You can position the new lookup attribute on the Account form wherever it makes most sense for your users.

1.On the Entity: Account form, under Details, click Forms and Views, and then in the list, double-click Form.

2.Select the section where you want to add the Contract lookup attribute. To select a section, click the section header, and a green line is displayed surrounding the section.

3.Click Add Fields. Your new lookup attribute appears on the list.

4.Select Contract, and then click OK.

5.Click Save, which will leave the Form: Account form open. Keep this form open, because you will use it in the next procedure.
Top of pageTop of page
Test your new lookup field

Before you publish a customization to a form, preview it in all the modes that will use the form so that you can verify that it works as you expect.

1.On the Form: Account form, on the Preview menu, click Create Form.
2.Click the Lookup button next to the Contract field. If you have created any records in the Contract entity, the list appears. Close the Lookup Records dialog box, and then, on the File menu, click Close to close the preview window.

3.On the Form: Account form, on the Preview menu, click Update Form, and then repeat step 2.
4.Click Save and Close.

5.On the Entity: Account form, click Save and Close.
Top of pageTop of page
Publish your customization

For your users to see the changes you’ve made, you must publish the customization.
•On the Customize Entities page, on the Actions toolbar, click Publish.

Thursday, October 28, 2010

Add Different Colors In Bar Chat In SSRS Report

01.Go to Chart Properties
02.Then Go Color and Click Expression.
03.Change Expression as follows.
=IIF(Fields!WeekDate.Value <(DateAdd("d", -7,Now().Today())),"RoyalBlue","Gold")

Tuesday, October 19, 2010

Update Plugin to CRM

01. Run Plug in Registration tool in CRM sdk.
02.Create connection and connect appropiate organization.
03.Register dll as Load Registration.
04.Create new Step for given name in Entity and Set Message as Create.

Create CRM plugin to Update Account Object Based On Address/ CRM 4

public class AccountCreatePlugin : IPlugin
public void Execute(IPluginExecutionContext context)
DynamicEntity entity = null;

// Check if the input parameters property bag contains a target
// of the create operation and that target is of type DynamicEntity.
if (context.InputParameters.Properties.Contains("Target") &&
context.InputParameters.Properties["Target"] is DynamicEntity)
// Obtain the target business entity from the input parmameters.
entity = (DynamicEntity)context.InputParameters.Properties["Target"];

// Verify that the entity represents an account.
if (entity.Name != EntityName
.ToString()) { return; }

//Get Address ID
if (context.OutputParameters.Properties.Contains("id"))
Guid regardingobjectid =
new Guid(context.OutputParameters.Properties["id"].ToString());
string regardingobjectidType = EntityName.customeraddress.ToString();

ColumnSet accountColumns = new ColumnSet();
// accountColumns.AddColumn("Account_CustomerAddress");
ICrmService service = (ICrmService)context.CreateCrmService(true);
customeraddress crmaddress =
(customeraddress)service.Retrieve(regardingobjectidType, regardingobjectid, accountColumns);

//Check Address is Belong to Account

if (crmaddress.objecttypecode.Value == EntityName.account.ToString())

ColumnSet accountColumns2 = new ColumnSet();

regardingobjectidType = crmaddress.objecttypecode.Value;
regardingobjectid = crmaddress.parentid.Value;

account crmaccount =
(account)service.Retrieve(regardingobjectidType, regardingobjectid, accountColumns2);

//Update Account Object
crmaccount.address1_city = crmaddress.city;




catch (System.Web.Services.Protocols.SoapException ex)
throw new Exception("An error occurred in the AccountCreateHandler plug-in.", ex);

Create CRM plugin to Create Address After Account Object Create CRM 4

namespace AccountCreatePlugin
public class AccountCreatePlugin : IPlugin
public void Execute(IPluginExecutionContext context)
DynamicEntity entity = null;

// Check if the input parameters property bag contains a target
// of the create operation and that target is of type DynamicEntity.
if (context.InputParameters.Properties.Contains("Target") &&
context.InputParameters.Properties["Target"] is DynamicEntity)
// Obtain the target business entity from the input parmameters.
entity = DynamicEntity)context.InputParameters.Properties["Target"];

// Verify that the entity represents an account.
if (entity.Name != EntityName.account
.ToString()) { return; }


//Create Address Object
customeraddress address = new customeraddress();
address.line1 = "Line 1";
address.line2 = "Line 2";
address.city = "City";
address.stateorprovince = "State";
address.postalcode = "Zip";
address.country = "Sri lanka";

if (context.OutputParameters.Properties.Contains("id"))
//Get Guid
Guid regardingobjectid =
new Guid(context.OutputParameters.Properties["id"].ToString());
string regardingobjectidType = EntityName.customeraddress.ToString();

address.parentid = new Lookup();
address.parentid.type = EntityName.account.ToString();
address.parentid.Value = regardingobjectid;

//sets the objecttypecode value to that of the account system
address.objecttypecode = new EntityNameReference();

address.objecttypecode.Value = EntityName.account.ToString();


ICrmService service = (ICrmService)context.CreateCrmService(true);

catch (System.Web.Services.Protocols.SoapException ex)
throw new Exception("An error occurred in the AccountCreateHandler plug-in.", ex);



Sunday, October 10, 2010

Disable Back Button Not Include TextArea Or Input

<script type="text/javascript">

if (typeof window.event != 'undefined')
document.onkeydown = function()

if ((event.srcElement.tagName.toUpperCase() != 'TEXTAREA')|| (event.srcElement.tagName.toUpperCase() != 'INPUT'))
return (event.keyCode != 8);
document.onkeypress = function(e)

if (e.target.nodeName.toUpperCase() != 'TEXTAREA')
return (e.keyCode != 8);


Wednesday, October 6, 2010

Ajax Calender Extender Add To Grid View

 Calender not Display Properly within grid. So Add hidden textbox as target Control and set visibility false.
add calender extender and hidden text box within div . set div position relative. Then set hidden textbox date to textbox date using  OnClientDateSelectionChanged function as follows.

 <style type="text/css">
  <script type="text/javascript">
        function checkDate(sender, args) {
            if (sender._selectedDate > new Date()) {
                alert("You cannot select a Future Date!");
                sender._selectedDate = new Date();
                // set the date back to the current date


            var hiddenId=(sender._element.id);
            var elem = hiddenId.split('_');
            var textId = elem[0] + '_' + elem[1] + '_txtChequeDate';
            document.getElementById(textId).value = document.getElementById(hiddenId).value;

///---------------------------In Grid View
<asp:TemplateField HeaderText="ChequeDate">
                                                        <asp:TextBox ID="txtChequeDate" runat="server"  CssClass="Textboxstyle" Enabled="false"
                                                            TabIndex="17" Width="100px"></asp:TextBox>
                                                        <div style="padding: 0; position: relative;" >
                                                             <cc1:CalendarExtender ID="calDocDate" runat="server" TargetControlID="hidChequeDate"
                                                                PopupButtonID="btnChequeDate" OnClientDateSelectionChanged="checkDate2"  />
                                                                 <asp:TextBox ID="hidChequeDate"    Width="0px" Height="0px" runat="server" CssClass="hiddenCol"  />
                                                    <td valign="top">
                                                        <asp:Button ID="btnChequeDate" runat="server" BorderStyle="None" BorderWidth="0px"
                                                            CssClass="calender" Enabled="false" TabIndex="18" />

Monday, September 27, 2010

Increase IIS Performance

Enable HTTP Keep-Alives
1 One way to help your IIS server perform optimally is to make sure that HTTP Keep-Alives are enabled. Although IIS 6.0 enables Keep-Alives by default, this setting makes such a big difference that it’s worth it to make sure that they haven’t been turned off.
The idea behind Keep-Alives is simple. As you probably know, most Web pages are made up of multiple elements. For example, a page might consist of an HTML document and multiple images. In order to display a Web page, a Web browser must download all of the page’s various elements to a local cache. This means that most of the time, a browser must download multiple files in order to display a single Web page.
Normally, when a Web browser downloads a file, it must open a connection to the Web server, download the file, and then close the connection. Since a Web page is usually made up of multiple files, this is very inefficient. There is absolutely no reason to close the connection if the Web browser is just going to have to open it again in order to download the next file. If the HTTP Keep-Alives option is enabled, then IIS holds the connection open so that a Web browser can download multiple files without having to open and close the connection each time.
How to do it: To enable the HTTP Keep-Alives option, open the IIS Manager and navigate through the console tree to Internet Information Services || Web Sites | your Web site. Right-click on your Web site and select the Properties command from the context menu. When you do, you will see the site’s Properties sheet (see Figure 1). The Enable HTTP Keep-Alives checkbox is located on the Web Site tab.

Figure 1 Enable Keep-Alives 

Adjust Connection Timeouts
2 While IIS can hold an HTTP connection open while a client downloads multiple files, you don’t want to hold the connection open indefinitely. By default, IIS 6.0 is configured to terminate a connection after 120 seconds of inactivity. This is a shorter period than was used in previous versions of IIS for a couple of reasons. First, IIS uses about 10KB of memory for each connection just to keep track of the connection. Terminating idle connections frees up memory. Second, having a short timeout period reduces the potential for denial of service attacks.
At the same time though, a 120-second idle period may or may not be optimal for your organization. Shorter timeout periods usually increase the server’s performance, but performance will degrade if a client’s connection is terminated prematurely.
The only way to determine the optimal timeout period for your server is to use the Performance Monitor to track the Current Connections, Maximum Connections, and Total Connection Attempts counters associated with the Web service performance object. Watch these counters until you have a good idea of the normal values for your organization. Then try incrementally lowering the timeout value, and watching the counters for a few days to see how they are affected. The idea is that you want to find the point at which the Current Connections and Maximum Connections counters reach their lowest average value without driving up the total connection attempts.
How to do it: You can find the timeout value on the Web Site tab of a site’s Properties sheet just below the Enable HTTP Keep-Alives checkbox. Change the value to the value you want to try.

Enable HTTP Compression
3 Another way to improve performance is to compress the pages that IIS is serving. Of course, compression can be a trade-off because it conserves bandwidth but consumes CPU time and disk space.
The trick to using compression effectively is to understand that in IIS not all files are created equal. For example, suppose that you are hosting a Web site made up mostly of static HTML pages. Compressing static pages requires a minimal effort on the part of the server because the pages can be compressed and then cached. The next time someone requests the page, IIS doesn’t have to compress it again; it can just pull the already compressed page from the cache. I recommend always compressing static pages unless your server is low on CPU resources or disk space. Dynamic pages, on the other hand, can’t really be cached. This means that IIS has to compress the dynamic pages each time that they are requested. If a site gets a lot of traffic, this can mean a lot of extra work for the server.
Just because compressed copies of dynamic pages can’t be cached does not mean that you shouldn’t compress dynamic pages. Dynamic page compression certainly does have its place. If you have a server that has a lightly used CPU, but is low on bandwidth, then it is a perfect candidate for HTTP compression.
You can compress both static and dynamic pages. In either case, you will need to verify that the temporary files are being stored in a suitable location. By default, temporary files will consume up to 95MB of space in the %windir%\IIS Temporary Compressed Files folder. When the 95MB limit has been reached, the older files will be overwritten by newer files.
How to do it: To enable HTTP compression, right-click on the Internet Information Services Manager’s Web Sites container and select the Properties command from the resulting context menu. When the Web Sites Properties sheet appears, select the Service tab. You can compress static files by selecting the Compress static files checkbox (which enables compression on htm, html, and txt files by default). Likewise, you can compress dynamic pages by selecting the Compress application files checkbox shown in Figure 2 (which enables compression on .asp, .dll, and .exe files by default). You’ll also see the option of changing the amount of space consumed by temporary files.

Figure 2 Compress Application Files 
You can modify the list of file extensions IIS will include in compression. To add one or more file types to the server-wide static compression configuration, open a command prompt and execute the following commands:
c:\inetpub\adminscripts>cscript adsutil.vbs 
SET W3SVC/Filters/Compression/Deflate/
HcFileExtensions "htm html txt newext" 

c:\inetpub\adminscripts>cscript adsutil.vbs 
SET W3SVC/Filters/Compression/gzip/HcFileExtensions 
"htm html txt newext"
"Newext" is the extension of the new file type you want to compress. You can add multiple file types separated by spaces.
To remove one or more file types from the server-wide static compression configuration, repeat the previous two commands, leaving out the file type you want to remove.
If you want to add one or more file types to the server-wide dynamic compression configuration, open a command prompt and type the two commands that are shown here:
c:\inetpub\adminscripts>cscript adsutil.vbs 
SET W3SVC/Filters/Compression/Deflate/
HcScriptFileExtensions "asp dll exe newext" 

c:\inetpub\adminscripts>cscript adsutil.vbs 
SET W3SVC/Filters/Compression/gzip/
HcScriptFileExtensions "asp dll exe newext"
Once again, "newext" is the extension of the new file type you want to compress. You can add multiple file types separated by spaces. You will have to restart IIS before compression will take effect.

Grow a Web Garden
4 One way that you can increase an application pool’s performance, especially if your infrastructure includes general latency with back-end data sources, is by assigning multiple worker processes to it. The result is called a Web garden. There are a couple of benefits to Web gardens. First, they reduce resource contention. Second, if a Web application causes a worker process to hang (such as caused by a script in an infinite loop), then the other worker processes can keep servicing requests.
How to do it: You can set the number of worker processes by right-clicking on an application pool and selecting the Properties command from the resulting context menu. The Web garden setting is found on the resulting Properties sheet’s Performance tab shown in Figure 3.

Figure 3 AppPool Properties 

Adjust the IIS Object Cache TTL
5 IIS caches any objects that have been requested. Each object within the cache has a time to live (TTL) value associated with it. By default, the TTL value is set at 30 seconds. This means that if an object in the cache hasn’t been used in the last 30 seconds, it is removed. A 30-second TTL may not always be appropriate, however. For example, if all of the pages on your site are dynamic, then IIS doesn’t really benefit much from caching, so you could free up some memory by shortening the TTL. Likewise, if the server is short on memory, then shortening the TTL is a good way to reclaim some memory for other functions. On the other hand, if your server has plenty of free memory and most of the pages are static, then you might be able to improve efficiency by increasing the TTL.
Unfortunately, the only way of adjusting the TTL is by editing the registry. Of course if you make a serious mistake editing the registry, you can cause Windows® or your applications to fail, so make sure you have a full system backup before continuing.
How to do it: Open the Registry Editor and navigate to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\InetInfo\Parameters. Now, right-click on the Parameters subkey and select the New | DWORD Value commands from the resulting shortcut menus. In the New Value dialog box, enter ObjectCacheTTL. Now, right-click on the value that you just created and select the Modify command. Set the base to Decimal and then enter the new TTL time (in seconds) into the Value Data box. You can set the TTL between 0 (no caching) and 4,294,967,295 (the maximum possible time limit, which indicates unlimited caching).

6 We’ve all seen examples of poorly written code that causes memory leaks. What some people don’t realize is that Web sites can contain leaky code, too. Leaky code can really impact IIS performance over time as more and more memory drains away. One way of limiting the effects of a memory leak is to recycle the worker processes and memory at the application-pool level.
IIS recycles the worker process every 299 hours by default, but you can gain tighter control over this. You can schedule the recycle process to occur at a certain interval, a specific time of day, or after a certain number of requests. You can also configure memory to be recycled once a certain threshold has been reached.
[Editor's Update - 11/1/2005:IIS recycles the worker process every 29 hours by default.]
How to do it: You can access the interface used to control recycling by right-clicking on the application pool that contains the leaky Web application, and selecting the properties command from the resulting shortcut menu. The recycling options exist on the Recycling tab of the AppPool’s Properties sheet, as you see in Figure 4.

Figure 4 Recycling Worker Processes 

Limit Queue Length
7 Queue length seems to be a touchy subject among IIS administrators, but in my opinion, it’s sometimes better to just let some visitors to your site leave rather than keep them waiting. When IIS receives a request, the request is placed into a queue and is then serviced. If requests come in more quickly than the server can service them, then the queue length grows because requests are added to the queue faster than they are being serviced. This in itself isn’t necessarily a bad thing. It’s normal for Web sites to get traffic in spurts. For example, a site might receive ten simultaneous requests one minute and only get two requests the next minute. Having a queue structure in place ensures that no requests are lost and that all of the requests are eventually serviced.
There comes a point when enough is enough though. If you’ve got 10,000 items in the queue and new requests continue to pour in, then the chances of IIS catching up with the requests any time soon are pretty slim. In these situations, it’s usually better to put a stop to new requests until the server has a chance to catch up. Imagine if there was no limit to the server’s queue length. Someone who wanted to launch a denial of service attack could flood the server with requests until the hard disk filled up. Limiting the queue length also ensures that anyone whose request is queued will be serviced within a reasonable amount of time. Everybody else will receive a notice indicating that the server is busy. Request queues service an entire application pool rather than an individual Web site.
How to do it: To change the request queue length, open the Internet Information Services Manager, right-click on the application pool that you want to adjust the queue length for, and select the Properties command from the resulting shortcut menu. When you do, you will see the AppPool’s Properties sheet that you saw in Figure 3.
The Request Queue Limit option is found on the Properties sheet’s Performance tab. By default, the queue limit is set at 1,000, but you can adjust the queue length to meet your needs.

Shift Priority to the Working Set
8 Servers running Windows Server™ 2003 are configured by default to give preference to the file system cache over the working set when allocating memory. Microsoft does this because Windows benefits from having a large file system cache. Being that IIS rides on top of the Windows operating system, it also benefits from having a large file system cache. If your server is a dedicated IIS Server, though, you might see better performance if you shift priority to the working set instead. The reason behind this is if preference is given to the file system cache, the pageable code is often written to virtual memory. The next time this information is needed, something else must be paged to virtual memory and the previously paged information must be read into physical memory before it can be used. This results in very slow processing.
How to do it: To shift the machine’s priority to the working set, open the Control Panel and choose the System option. When the System Properties sheet appears, select the Advanced tab and then click the Settings button found in the Performance section. This will cause Windows to display the Performance Options Properties sheet. Select the Advanced tab and then select the Programs option in the Memory usage section, as shown in Figure 5.

Figure 5 Performance Options 

Add Memory
9 The addition of physical memory is one of the best performance enhancements you can make. To optimize available memory, data is moved back and forth between RAM and disk-based virtual memory in a process known as paging. The more RAM the server machine has, the less paging will occur, and that’s good because paging is extremely inefficient and causes the machine to run much slower than it would if everything could fit into RAM. A little paging is normal, even on machines with plenty of RAM, but excessive paging will kill a machine’s performance. Not only does the machine have to stop and wait for the paging operation to complete, but the paging operation itself is processor intensive.
In addition to adding memory you can create page files on multiple hard disks. Windows requires your page file to be 1.5 times the size of your system’s RAM. However, not all of that space has to exist within a single file. For example, if you have a server with four hard drives and 1GB of RAM, then placing a 384MB page file on each of the four drives would usually be more efficient than placing a 1.5GB page file on a single disk.

Use Disk Striping
10 Although disk striping isn’t technically an IIS performance tweak, it can go a long way toward helping IIS to be more efficient. Disk striping spans files across multiple hard drives in an effort to achieve the combined performance of multiple drives. For example, if a volume is striped across five physical hard drives, then data can be read and written at approximately five times the speed that it could be if it existed on a single drive, because all five drives are being used simultaneously.
In the real world, you won’t get five times the performance by using five drives, because you lose some performance to the overhead of managing multiple drives. Some stripe sets also sacrifice some speed and capacity in order to achieve a degree of fault tolerance.
While including disk striping in your IIS architecture and design can help you achieve performance gains, unfortunately the concept of disk striping and other advanced disk configurations is a bit more complex than .

Tuesday, September 21, 2010

button click event oddity in FireFox(enter key press fire hidden button event in firefox asp.net)

solution: declare the hidden button with UseSubmitBehavior="false": this will make the button postback with the ASP.NET postback model and this should do the trick.
<div style="display:none;">
    <asp:Button id="btnHidden" runat="server"

Monday, September 20, 2010

Enable ASPX Compression in IIS

Suggest taking a a backup copy of the file C:\Windows\System32\inetsrv\MetaBase.xml

WARNING: If you edit the metabase incorrectly, you can cause serious problems that may require you to reinstall any product that uses the metabase. Microsoft cannot guarantee that problems that result if you incorrectly edit the metabase can be solved. Edit the metabase at your own risk.

NOTE: Always back up the metabase before you edit it.

To enable IIS 5.0 to compress .aspx pages, follow these steps:
  1. Open a command prompt.
  2. Type net stop iisadmin, and then press ENTER.
  3. Type cd C:\InetPub\adminscripts, and then press ENTER.
  4. Type the following, and then press ENTER:
    CSCRIPT.EXE ADSUTIL.VBS SET W3Svc/Filters/Compression/GZIP/HcScriptFileExtensions "asp" "dll" "exe" "aspx"
  5. Type the following, and then press ENTER:
    CSCRIPT.EXE ADSUTIL.VBS SET W3Svc/Filters/Compression/DEFLATE/HcScriptFileExtensions "asp" "dll" "exe" "aspx"
  6. Type net start w3svc, and then press ENTER.

Friday, September 17, 2010

ScriptManager.RegisterStartupScript in User Control Not working

Remove Update Panel In User Control or page.
ScriptManager.RegisterStartupScript work Properly

Wednesday, August 25, 2010

To avoid ThreadAbortException while Redirect

You don't need to put the redirect in a try-catch block. Just replace all calls to Response.Redirect(url) with the following two lines:

Response.Redirect(url, false);

That will avoid the exception being thrown and gracefully end execution of the thread and event chain.

Tuesday, August 24, 2010

Iframe Reload


Thursday, August 19, 2010

The maximum report processing jobs limit configured by your system administrator has been reached.

1) Dispose report object and close it.
2)Increate the PrintJobLimit in regedit. Default value = 75.(Set -1 for unlimited)

Wednesday, August 18, 2010

Track Collapse/ Expand event of AJAX Collapsible Panel Extender to call javascript

Add This Code as java script................

 function pageLoad(sender, args) {

    function expandHandler(sender, args) {
        document.getElementById(focustextBox).focus();//ANY EVENT

    function collapseHandler(sender, args) {
      //  document.getElementById("tdMenu").style.width = "20px";

Thursday, August 12, 2010

Visual Studio 2008 and SQL Server 2008 - Schema Compare

To compare SQL Server 2008 development database with another on a third party server to make sure they are in sync, unfortunetly even on Visual Studio 2008 SP1 the schema compare does not work - "Schema Compare does not support SQL Server 2008".

Today a RC1 of the Visual Studio Team System 2008 Database Edition GDR was released; this fixes the schema compare amongst other things.

Link is here: http://www.microsoft.com/downloads/details.aspx?FamilyID=bb3ad767-5f69-4db9-b1c9-8f55759846ed&displaylang=en

Wednesday, August 11, 2010

Add Control To Crystal Report Viewer Toolbar

Call This Method In To Page Loload(It will Remove Business Object Image)
private void customizeToolbar()
            Control ts = CrystalReportViewer1.Controls[2];
            if (ts.ToString().Contains("ViewerToolbar"))
                var BtnBack = new Button();
                BtnBack.ID = "btnBack";
                BtnBack.Text = "Back";
                BtnBack.ToolTip = "Back";
                BtnBack.Click += Button1_Click;
                ts.Controls.AddAt(16, BtnBack);

Friday, July 30, 2010

User Cursor to Set Update One Table Coloum Values To Another Table

In This Example replace Product Table TotalStockU1  values with StockRecord table StockU1 values.

DECLARE @name decimal(13, 4) 
DECLARE @product varchar(24)

(SELECT RD.StockRecord.StockU1,RD.StockRecord.ProductCode
FROM RD.StockRecord INNER JOIN RD.Product ON
RD.StockRecord.ProductCode = RD.Product.ProductCode and RD.StockRecord.BusinessUnit=RD.Product.BusinessUnit
WHERE RD.StockRecord.ProductCode = RD.Product.ProductCode and RD.StockRecord.BusinessUnit='TEST')

OPEN db_cursor 
FETCH NEXT FROM db_cursor INTO @name,@product 

      UPDATE RD.Product     
        SET TotalStockU1 =@name        
         RD.Product.BusinessUnit='TEST' and RD.Product.ProductCode=@product;
       FETCH NEXT FROM db_cursor INTO @name,@product   

CLOSE db_cursor 
DEALLOCATE db_cursor

Saturday, July 17, 2010

Improve ASP.net Application Performance


1. Turn off Tracing unless until required.
2. Turn off session state in web.config file or at least for a page if there is no sessions.
3 set debug=false
4. Increase the Pool "Packet size" for transferring large blob or image fields
In connection string set "Packet Size= Required number". Performance decreases if the Packet size is huge for small amount of data transfers.

Web Application

1) Turn off Tracing unless until required
Tracing is one of the wonderful features which enable us to track the application's trace and the sequences. However, again it is useful only for developers and you can set this to "false" unless you require to monitor the trace logging.
How it affects performance:
Enabling tracing adds performance overhead and might expose private information, so it should be enabled only while an application is being actively analyzed.
When not needed, tracing can be turned off using

2) Turn off Session State, if not required
One extremely powerful feature of ASP.NET is its ability to store session state for users, such as a shopping cart on an e-commerce site or a browser history.
How it affects performance:
Since ASP.NET Manages session state by default, you pay the cost in memory even if you don't use it. I.e. whether you store your data in in-process or on state server or in a Sql Database, session state requires memory and it's also time consuming when you store or retrieve data from it.
You may not require session state when your pages are static or when you do not need to store information captured in the page.
In such cases where you need not use session state, disable it on your web form using the directive,
<@%Page EnableSessionState="false"%>
In case you use the session state only to retrieve data from it and not to update it, make the session state read only by using the directive,
<@%Page EnableSessionState ="ReadOnly"%>

3) Disable View State of a Page if possible
View state is a fancy name for ASP.NET storing some state data in a hidden input field inside the generated page. When the page is posted back to the server, the server can parse, validate, and apply this view state data back to the page's tree of controls.
View state is a very powerful capability since it allows state to be persisted with the client and it requires no cookies or server memory to save this state. Many ASP.NET server controls use view state to persist settings made during interactions with elements on the page, for example, saving the current page that is being displayed when paging through data.
How it affects performance:
? There are a number of drawbacks to the use of view state, however.
? It increases the total payload of the page both when served and when requested. There is also an additional overhead incurred when serializing or deserializing view state data that is posted back to the server.
? View state increases the memory allocations on the server. Several server controls, the most well known of which is the DataGrid, tend to make excessive use of view state, even in cases where it is not needed.
Pages that do not have any server postback events can have the view state turned off.
The default behavior of the ViewState property is enabled, but if you don't need it, you can turn it off at the control or page level. Within a control, simply set the EnableViewState property to false, or set it globally within the page using this setting:
<%@ Page EnableViewState="false" %>
If you turn view state off for a page or control, make sure you thoroughly test your pages to verify that they continue to function correctly.

4) Set debug=false in web.config
When you create the application, by default this attribute is set to "true" which is very useful while developing. However, when you are deploying your application, always set it to "false".
How it affects performance:
Setting it to "true" requires the pdb information to be inserted into the file and this results in a comparatively larger file and hence processing will be slow.
Therefore, always set debug="false" before deployment.

5) Avoid Response.Redirect
Response.Redirect () method simply tells the browser to visit another page.
How it affects performance:
Redirects 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. Instead of telling the browser to redirect, it simply changes the "focus" on the Web server and transfers the request. This means you don't get quite as many HTTP requests coming through, which therefore eases the pressure on your Web server and makes your applications run faster.

? ".transfer" process can work on only those sites running on the server. Only Response.Redirect can do that.
? Server.Transfer maintains the original URL in the browser. This can really help streamline data entry techniques, although it may make for confusion when debugging
5. A) To reduce CLR Exceptions count, Use Response.Redirect (".aspx", false) instead of response.redirect (".aspx").

6) Use the String builder to concatenate string
How it affects performance:
String is Evil when you want to append and concatenate text to your string. All the activities you do to the string are stored in the memory as separate references and it must be avoided as much as possible.
i.e. When a string is modified, the run time will create a new string and return it, leaving the original to be garbage collected. Most of the time this is a fast and simple way to do it, but when a string is being modified repeatedly it begins to be a burden on performance: all of those allocations eventually get expensive.
Use String Builder when ever string concatenation is needed so that it only stores the value in the original string and no additional reference is created.

7) Avoid throwing exceptions
How it affects performance:
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.
You can use as many try/catch blocks as you want. Using exceptions gratuitously is where you lose performance. For example, you should stay away from things like using exceptions for control flow.

8) Use Finally Method to kill resources
?The finally method gets executed independent of the outcome of the Block.
?Always use the finally block to kill resources like closing database connection, closing files and other resources such that they get executed independent of whether the code worked in Try or went to Catch.

9) Use Client Side Scripts for validations
User Input is Evil and it must be thoroughly validated before processing to avoid overhead and possible injections to your applications.
How It improves performance:
Client site validation can help reduce round trips that are required to process user's request. In ASP.NET you can also use client side controls to validate user input. However, do a check at the Server side too to avoid the infamous Javascript disabled scenarios.

10) Avoid unnecessary round trips to the server
How it affects performance:
Round trips significantly affect performance. They are subject to network latency and to downstream server latency. Many data-driven Web sites heavily access the database for every user request. While connection pooling helps, the increased network traffic and processing load on the database server can adversely affect performance.
? Keep round trips to an absolute minimum
? Implement Ajax UI whenever possible. The idea is to avoid full page refresh and only update the portion of the page that needs to be changed

11) Use Page.ISPostBack
Make sure you don't execute code needlessly. Use Page.ISPostBack property to ensure that you only perform page initialization logic when a page is first time loaded and not in response to client postbacks.

12) Include Return Statements with in the Function/Method
How it improves performance
Explicitly using return allows the JIT to perform slightly more optimizations. Without a return statement, each function/method is given several local variables on stack to transparently support returning values without the keyword. Keeping these around makes it harder for the JIT to optimize, and can impact the performance of your code. Look through your functions/methods and insert return as needed. It doesn't change the semantics of the code at all, and it can help you get more speed from your application.

13) Use Foreach loop instead of For loop for String Iteration
Foreach is far more readable, and in the future it will become as fast as a For loop for special cases like strings. Unless string manipulation is a real performance hog for you, the slightly messier code may not be worth it.

14) Avoid Unnecessary Indirection
How it affects performance:
When you use byRef, you pass pointers instead of the actual object.
Many times this makes sense (side-effecting functions, for example), but you don't always need it. Passing pointers results in more indirection, which is slower than accessing a value that is on the stack.
When you don't need to go through the heap, it is best to avoid it there by avoiding indirection.

15) Use "ArrayLists" in place of arrays
How it improves performance
An ArrayList as everything that is good about an array PLUS automatic sizing, Add, Insert, Remove, Sort, Binary Search. All these great helper methods are added when implementing the IList interface.
The downside of an ArrayList is the need to cast objects upon retrieval.

16) Always check Page.IsValid when using Validator Controls
Always make sure you check Page.IsValid before processing your forms when using Validator Controls.

17) 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. Don't cache all the data in the grid.

18) Store your content by using caching
How it improves performance:
ASP.NET allows you to cache entire pages, fragment of pages or controls. You can cache also variable data by specifying the parameters that the data depends. By using caching you help ASP.NET engine to return data for repeated request for the same page much faster.
When and Why Use Caching:
A Proper use and fine tune of caching approach of caching will result on better performance and scalability of your site. However improper use of caching will actually slow down and consume lots of your server performance and memory usage.
Good candidate to use caching is if you have infrequent chance of data or static content of web page.

19) Use low cost authentication
Authentication can also have an impact over the performance of your application. For example passport authentication is slower than form-base authentication which in here turn is slower than Windows authentication.

20) Minimize the number of web server controls
How it affects performance:
The use of web server controls increases the response time of your application because they need time to be processed on the server side before they are rendered on the client side.
One way to minimize the number of web server controls is to taking into consideration, the usage of HTML elements where they are suited, for example if you want to display static text.

21) Avoid using unmanaged code
How it affects performance:
Calls to unmanaged code are a costly marshaling operation.
Try to reduce the number calls between the managed and unmanaged code. Consider to do more work in each call rather than making frequent calls to do small tasks.

22) Avoid making frequent calls across processes
If you are working with distributed applications, this involves additional overhead negotiating network and application level protocols. In this case network speed can also be a bottleneck. Try to do as much work as possible in fewer calls over the network.

23) Cleaning Up Style Sheets and Script Files
? A quick and easy way to improve your web application's performance is by going back and cleaning up your CSS Style Sheets and Script Files of unnecessary code or old styles and functions. It is common for old styles and functions to still exist in your style sheets and script files during development cycles and when improvements are made to a website.
? Many websites use a single CSS Style Sheet or Script File for the entire website. Sometimes, just going through these files and cleaning them up can improve the performance of your site by reducing the page size. If you are referencing images in your style sheet that are no longer used on your website, it's a waste of performance to leave them in there and have them loaded each time the style sheet is loaded.
? Run a web page analyzer against pages in your website so that you can see exactly what is being loaded and what takes the most time to load.

24) Design with ValueTypes
Use simple structs when you can, and when you don't do a lot of boxing
and unboxing.
ValueTypes are far less flexible than Objects, and end up hurting performance if used incorrectly. You need to be very careful about when you treat them like objects. This adds extra boxing and unboxing overhead to your program, and can end up costing you more than it would if you had stuck with objects.

25) Minimize assemblies
Minimize the number of assemblies you use to keep your working set small. If you load an entire assembly just to use one method, you're paying a tremendous cost for very little benefit. See if you can duplicate that method's functionality using code that you already have loaded.

26) Encode Using ASCII When You Don't Need UTF
By default, ASP.NET comes configured to encode requests and responses as UTF-8.
If ASCII is all your application needs, eliminated the UTF overhead can give you back a few cycles. Note that this can only be done on a per-application basis.

27) Avoid Recursive Functions / Nested Loops
These are general things to adopt in any programming language, which consume lot of memory. Always avoid Nested Loops, Recursive functions, to improve performance.

28) Minimize the Use of Format ()
When you can, use toString () instead of format (). In most cases, it will provide you with the functionality you need, with much less overhead.

29) Place StyleSheets into the Header
Web developers who care about performance want browser to load whatever content it has as soon as possible. This fact is especially important for pages with a lot of content and for users with slow Internet connections. When the browser loads the page progressively the header, the logo, the navigation components serve as visual feedback for the user.
When we place style sheets near the bottom part of the html, most browsers stop rendering to avoid redrawing elements of the page if their styles change thus decreasing the performance of the page. So, always place StyleSheets into the Header

30) Put Scripts to the end of Document
Unlike StyleSheets, it is better to place scripts to the end of the document. Progressive rendering is blocked until all StyleSheets have been downloaded. Scripts cause progressive rendering to stop for all content below the script until it is fully loaded. Moreover, while downloading a script, browser does not start any other component downloads, even on different hostnames.
So,always have scripts at the end of the document.

31) Make JavaScript and CSS External
Using external files generally produces faster pages because the JavaScript and CSS files are cached by the browser. Inline JavaScript and CSS increases the HTML document size but reduces the number of HTTP requests. With cached external files, the size of the HTML is kept small without increasing the number of HTTP requests thus improving the performance.

Database Operations

1) Return Multiple Resultsets
The database code if has request paths that go to the database more than once then, these round-trips decreases the number of requests per second your application can serve.
Return multiple resultsets in a single database request, so that you can cut the total time spent communicating with the database. You'll be making your system more scalable, too, as you'll cut down on the work the database server is doing managing requests.

2) Connection Pooling and Object Pooling
Connection pooling is a useful way to reuse connections for multiple requests, rather than paying the overhead of opening and closing a connection for each request. It's done implicitly, but you get one pool per unique connection string. Make sure you call Close or Dispose on a connection as soon as possible. When pooling is enabled, calling Close or Dispose returns the connection to the pool instead of closing the underlying database connection.
Account for the following issues when pooling is a part of your design:
? Share connections
? Avoid per-user logons to the database
? Do not vary connection strings
? Do not cache connections

3) Use SqlDataReader Instead of Dataset wherever it is possible
If you are reading a table sequentially you should use the DataReader rather than DataSet. DataReader object creates a read only stream of data that will increase your application performance because only one row is in memory at a time.

4) Keep Your Datasets Lean
Remember that the dataset stores all of its data in memory, and that the more data you request, the longer it will take to transmit across the wire.
Therefore Only put the records you need into the dataset.

5) Avoid Inefficient queries
How it affects performance:
Queries that process and then return more columns or rows than necessary, waste processing cycles that could best be used for servicing other requests.

Cause of Inefficient queries:
? Too much data in your results is usually the result of inefficient queries.
? The SELECT * query often causes this problem. You do not usually need to return all the columns in a row. Also, analyze the WHERE clause in your queries to ensure that you are not returning too many rows. Try to make the WHERE clause as specific as possible to ensure that the least number of rows are returned.
? Queries that do not take advantage of indexes may also cause poor performance.

6) Unnecessary round trips
How it affects performance:
Round trips significantly affect performance. They are subject to network latency and to downstream server latency. Many data-driven Web sites heavily access the database for every user request. While connection pooling helps, the increased network traffic and processing load on the database server can adversely affect performance.
Keep round trips to an absolute minimum.

7) Too many open connections
Connections are an expensive and scarce resource, which should be shared between callers by using connection pooling. Opening a connection for each caller limits scalability.
To ensure the efficient use of connection pooling, avoid keeping connections open and avoid varying connection strings.

8) Avoid Transaction misuse
How it affects performance:
If you select the wrong type of transaction management, you may add latency to each operation. Additionally, if you keep transactions active for long periods of time, the active transactions may cause resource pressure.
Transactions are necessary to ensure the integrity of your data, but you need to ensure that you use the appropriate type of transaction for the shortest duration possible and only where necessary.

9) Avoid Over Normalized tables
Over Normalized tables may require excessive joins for simple operations. These additional steps may significantly affect the performance and scalability of your application, especially as the number of users and requests increases.

10) Reduce Serialization
Dataset serialization is more efficiently implemented in .NET Framework version 1.1 than in version 1.0. However, Dataset serialization often introduces performance bottlenecks.
You can reduce the performance impact in a number of ways:
? Use column name aliasing
? Avoid serializing multiple versions of the same data
? Reduce the number of DataTable objects that are serialized

11) Do Not Use CommandBuilder at Run Time
How it affects performance:
CommandBuilder objects such as as SqlCommandBuilder and OleDbCommandBuilder are useful when you are designing and prototyping your application. However, you should not use them in production applications. The processing required to generate the commands affects performance.
Manually create stored procedures for your commands, or use the Visual Studio® .NET design-time wizard and customize them later if necessary.

12) Use Stored Procedures Whenever Possible
?Stored procedures are highly optimized tools that result in excellent performance when used effectively.
?Set up stored procedures to handle inserts, updates, and deletes with the data adapter
?Stored procedures do not have to be interpreted, compiled or even transmitted from the client, and cut down on both network traffic and server overhead.
?Be sure to use CommandType.StoredProcedure instead of CommandType.Text

13) Avoid Auto-Generated Commands
When using a data adapter, avoid auto-generated commands. These require additional trips to the server to retrieve meta data, and give you a lower level of interaction control. While using auto-generated commands is convenient, it's worth the effort to do it yourself in performance-critical applications.

14) Use Sequential Access as Often as Possible
With a data reader, use CommandBehavior.SequentialAccess. This is essential for dealing with blob data types since it allows data to be read off of the wire in small chunks. While you can only work with one piece of the data at a time, the latency for loading a large data type disappears. If you don't need to work the whole object at once, using
Sequential Access will give you much better performance.

Thursday, July 15, 2010

Set Focus on Textbox in modalPopup Panel

Add following code in my Page_Load :
StringBuilder sb = new StringBuilder();
sb.Append("<script type=\"text/javascript\">\n");
sb.Append("function modalSetup() {\n");
sb.Append(String.Format("var modalPopup = $find('{0}');\n", ModalPopupExtender1.BehaviorID));
sb.Append("modalPopup.add_shown(SetFocusOnControl); }\n");
sb.Append("function SetFocusOnControl() {\n");
sb.Append(String.Format("var textBox1 = $get('{0}');\n", tbMyTextbox.ClientID));
Page.ClientScript.RegisterStartupScript(Page.GetType(), "Startup", sb.ToString());

Monday, July 12, 2010

ScriptManager.RegisterStartupScript Java Script Not Working With Response.Redirect

01. Remove  Response.Redirect("~/Error.aspx");
string redirectURL = Page.ResolveClientUrl("~/Error.aspx");
ScriptManager.RegisterStartupScript(Page, GetType(), "Script",
                                      "document.location = '" + redirectURL + "';", true);

Sunday, July 11, 2010

GridView with RadioButtonList

//In Onchange Event

Add   AutoPoseBack=true


protected void CheckBox1_CheckedChanged(object sender, EventArgs e){
foreach (GridViewRow row in GridView1.Rows)
CheckBox ch = (CheckBox) row.FindControl("CheckBox1");
ch.Checked = false;
CheckBox checkbox = (CheckBox)sender;
checkbox.Checked = true;
GridViewRow row = (GridViewRow)checkbox.NamingContainer;

Wednesday, July 7, 2010

Keypress event not working C#

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
MessageBox.Show(e.KeyChar.ToString(), "Your input");

IF NOT EVENT IS FIRE>>>>>>>>>>>>>>>>>>>>>
Need to set the KeyPreview Property of your Form to True so it will recognize the key press event.

Wednesday, June 30, 2010

getElementByID return always null calling from RegisterClientScriptBlock

Add  ClientScript.RegisterStartupScript instead of ClientScript.RegisterClientScriptBlock

The RegisterClientScriptBlock method inserts the client-side script immediately below the opening tag of the Page object's <form runat="server"> element. The code cannot access any of the form's elements because, at that time, the elements haven't been instantiated yet. This explains why hdnView variable had a null value in my case. The RegisterStartupScript method inserts the specified client-side script just before the closing tag of the Page object's <form runat="server"> element. The code can access any of the form's elements because, at that time, the elements have been instantiated. The choice of which method to use really depends on the "order" in which you want your script to be run by the browser when rendering the page.

Wednesday, June 23, 2010

Want to create an html link <a href=""></a> and Iframe using C# - dynamically

// Create a new HtmlAnchor control.
HtmlAnchor NewAnchorControl = new HtmlAnchor();

// Set the properties of the new HtmlAnchor control.
NewAnchorControl.Name = "NewAnchorControl";
NewAnchorControl.HRef = "http://www.microsoft.com";
NewAnchorControl.Target = "_blank";
NewAnchorControl.InnerHtml = "Microsoft Home";

// Add the new HtmlAnchor control to the Controls collection of the
// PlaceHolder control.

HtmlGenericControl frame1 = new HtmlGenericControl("iFrame");
frame1.Attributes.Add("runat", "server");
frame1.Attributes.Add("width", "100px");
frame1.Attributes.Add("height", "100px");
frame1.TagName = "iframe";
frame1.Attributes.Add("src", "http://www.microsoft.com");


Wednesday, June 16, 2010

problem with RegisterClientScriptBlock in UpdatePanles

The script tag registered for type 'ASP.projectviewer_asp' and key ###### has invalid characters outside of the script tags: <link href='####.css' type='text/css' rel='stylesheet' >. Only properly formatted script tags can be registered.

This Work fine -------------
page.ClientScript.RegisterStartupScript( page.GetType(),"CSS", " <link href='####.css' type='text/css' rel='stylesheet' >", false);

Tuesday, June 15, 2010

The partner transaction manager has disabled its support for remote/network transactions

1. Go to "Administrative Tools > Services"
2. Turn on the "Distribute Transaction Coordinator" Service if it is not running
If it is running and client application is not on the same computer as
the database server, on the computer running database server
1. Go to "Administrative Tools > Component Services"
2. On the left navigation tree, go to "Component Services > Computers
> My Computer" (you may need to double click and wait as some nodes
need time to expand)
3. Right click on "My Computer", select "Properties"
4. Select "MSDTC" tab
5. Click "Security Configuration"
5 Select Network DTC Access, Allow Inbound, Allow Outbound, No Authentication Required, and Enable XA Transactions

Wednesday, June 9, 2010

It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS.

We may get this error when trying to browse an asp.net application.

The debug information shows that "This error can be caused by a virtual directory not being configured as an application in IIS."

However, this error occurs primarily out of 2 scenarios.

1. When we create an new web application using visual studio.net, it automatically creates the virtual directory and configures it as an application. However, if we manually create the virtual directory and it is not configured as an application, then we will not be able to browse the application and may get the above error. The debug information we get as mentioned above, is applicable to this scenario.

To resolve it, Right Click on the virtual directory - select properties and then click on
"Create" next to the "Application" Label and the textbox. It will automatically create the "application" using the virtual directory's name. Now the application can be accessed.

2. When we have sub-directories in wer application, we can have web.config file for the sub-directory. However, there are certain properties which cannot be set in the web.config of the sub-directory such as authentication, session state (we may see that the error message shows the line number where the authentication or sessionstate is declared in the web.config of the sub-directory). The reason is, these settings cannot be overridden at the sub-directory level unless the sub-directory is also configured as an application (as mentioned in the above point).

Mostly we have the practice of adding web.config in the sub-directory if we want to protect access to the sub-directory files (say, the directory is admin and we wish to protect the admin pages from unathorized users).

But actually, this can be achieved in the web.config at the application's root level itself, by specifing the location path tags and authorization, as follows:-

<location path="Admin">



<allow roles="administrators" />

<deny users="*" />




However, if we wish to have a web.config at the sub-directory level and protect the sub-directory, we can just specify the Authorization mode as follows:-




<allow roles="administrators" />

<deny users="*" />




Wednesday, June 2, 2010

Change Theme Folder Style Sheet ASP.NET

01.Add New Style Sheet in to the theme folder.
02.Write Bellow Code in to the Code Behind.

string css = @"<link )="" +="" @="" app_themes="" blue="" css="" href="" rel="" stylesheet2.css="" stylesheet="" text="" this.resolveurl(="" type=""></link>";

ScriptManager.RegisterClientScriptBlock(this.Page, GetType(), "_calcss", css, false);

It Replace In .aspx Page Like>>>>>>>>>>>


</title><link href="App_Themes/Red/StyleSheet.css" type="text/css" rel="stylesheet" /><link href="App_Themes/Red/StyleSheet2.css" type="text/css" rel="stylesheet" /></head>

<form name="form1" method="post" action="WebForm1.aspx" id="form1">


<link href="/App_Themes/Blue/StyleSheet2.css" type="text/css" rel="stylesheet" />


Tuesday, June 1, 2010

While Saving the excel using workbook.saveAs getting the Exception from HRESULT: 0x800A03EC 02-18-2010, 1:59 AM

1. Login to the server as a administrator. 
2. Go to "Start" -> "Run" and enter "taskmgr" 
3. Go to the process tab in task manager and check "Show Processes from all 
4. If there are any "Excel.exe" entries on the list, right click on the 
entry and select "End Process" 
5. Close task manager. 
6. Go to "Start" -> "Run" and enter "services.msc" 
7. Stop the service automating Excel if it is running. 
8. Go to "Start" -> "Run" and enter "dcomcnfg" 
9. This will bring up the component services window, expand out "Console 
Root" -> "Computers" -> "DCOM Config" 
10. Find "Microsoft Excel Application" in the list of components. 
11. Right click on the entry and select "Properties" 
12. Go to the "Identity" tab on the properties dialog. 
13. Select "The interactive user." 
14. Click the "OK" button. 
15. Switch to the services console 
16. Start the service automating Excel17. Test you application again.
If Not
my service starts under local Administrator account
- on DCOM Config > MS Excel Application > Identity tab I've selected "This 
user" option and also entered Administrator's account 

Opening Office filetype from within update panel causes Security bar to block files. [INTERNET EXPLORER]

To FIX THIS--------------------

1. From Internet Explorer, click Tools, and then click Internet Options. The Internet Options dialog box appears.
2. Click the Security tab. The Internet Options dialog box shows your security levels and zones.
3. Select the Internet zone, and then click Custom Level. The Security Settings dialog box appears.
4. Scroll down to Downloads, and then select the Enable option for Automatic prompting for file downloads.

Tuesday, May 25, 2010

Microsoft JScript runtime error: AjaxControlToolkit requires ASP.NET Ajax 4.0 scripts

AjaxControlToolkit requires ASP.NET Ajax 4.0 scripts. Ensure the correct version of the scripts are referenced. If you are using an ASP.

changed this
<asp:scriptmanager id="ScriptManager1" runat="server"></asp:scriptmanager>
to this
<cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">cc1:ToolkitScriptManager>

Problem solved.

Locating the Component services manager in Vista

Com (plus) is not dead (yet). But the component services manager seems to have disappeared from the administrative tools in the Vista control panel. Nevertheless you can start the management console straight from windows\System32\comexp.msc.

or Run >>>  comexp.msc

The flowed transaction could not be unmarshaled. The following exception occurred: The MSDTC transaction manager's WS-AtomicTransaction protocol service 'Version10' is disabled and cannot unmarshal incoming transactions.

Marshal/Unmarshal problem in Ventura

01. Control pane------; Administrative Tools----; Component Services
02. Component Service----------Computers--------;My Computer
03. Right Click-------Properties-------MSDTC tab------;Security Configuration---------;allow Remote Clients