31 March 2008

Max Degree of Parallelism

The Max Degree of Parallelism or MAXDOP is a configuration indicating how the SQL Server optimizer will use the CPUs.

The value must be equal to the number of physical processors, not including hyperthreading.

One possible calculation formula is:

select case
         when cpu_count / hyperthread_ratio > 8 then 8
         else cpu_count / hyperthread_ratio
       end as optimal_maxdop_setting
from sys.dm_os_sys_info;

 


Configure via Management Studio:


1. Open SQL Server 2005 Management Studio
2- Once the tool loads, navigate to the intended server in the Object Explorer and right click on server name
3. Select the 'Properties' option
4. Select the 'Advanced' page from the left navigation
5. Review the configurations for the 'Parallelism' section


Configure via T-SQL Script:



sp_configure 'show advanced options', 1;
GO
RECONFIGURE WITH OVERRIDE;
GO
sp_configure 'max degree of parallelism', 8;
GO
RECONFIGURE WITH OVERRIDE;
GO

18 March 2008

T-SQL And Linq To Sql Reference

Blogger Tags:

Exists

1. T-SQL

select * from Orders o
where exists (select 1 from Product where ProductType = 'Memory'               
              and ProductId = o.ProductID)

2. Linq



using (MyDataContext dc = new MyDataContext())
{    
    var orders = from o in dc.Orders    
                  where (from p in dc.Products    
                         where p.ProductType == 'Memory'    
                         select p.ProductID).Contains(o.ProductID)
                  select o;
}

05 March 2008

How To avoid double click a button on Postback

A common problem in developing with asp.net is the user pressing more than once on a submit button.

One way to avoid this question is to use client side JavaScript to disable the button after the user clicked it. The only problem with this approach is if validators are being used. If the Page is not valid, the button will stay disabled and the user cannot press it again.

There is only one problem: When the button is disabled, the page is not submitted and the button event does not fires on the server.

Fortunately the validation library sets the Page_IsValid to false if validation fails or to true otherwise.
The JavaScript function to change the button image can be written as:

function ToggleButton(button, validationGroup)
{
   // If client validators not active
   if (typeof(Page_Validators) == "undefined")
   {
        SetWaitMode(button);
   }
 
   if (typeof(Page_ClientValidate) == 'function') 
   {
         // Force Page validation 
         Page_ClientValidate(validationGroup);                 
         
         // If validation passed
         if(Page_IsValid)
         {  
            SetWaitMode(button)       
         }
   }
   else
   {
        SetWaitMode(button);
   }
}


function SetWaitMode(button)
{
    button.src = "Shared/images/Wait.gif";
    document.forms[0].submit();
    
    window.setTimeout("DisableButton( '" + button.id  + "')", 0);           
 
}
 
function DisableButton(buttonID) 
{
    window.document.getElementById(buttonID).disabled = true;
}

This solution changes the button image, but doesn't solve the problem, since the user can still press the button.


A more elegant solution is to use two Divs, on with the wait image and other with the button. When the button is pressed it's Div is hidden and the one with the Wait image is shown.



<div id="btnSaveDiv2" runat="server" style="display: none; float: left">
    <img src="Shared/images/Wait.gif"></img>
</div>
<div id="btnSaveDiv1" runat="server" style="display: block; float: left">
    <asp:ImageButton runat="server" ID="btnSave" OnClientClick="javascript:ToggleButton(this, 'AddNewNoteValidationGroup')" ImageUrl="~/Common/images/layout/b_save.gif" OnClick="btnAddNote_Click" ValidationGroup="AddNewNoteValidationGroup" />
</div>


function ToggleButton(button, validationGroup)
{
   // If client validators not active
   if (typeof(Page_Validators) == "undefined")
   {
        DisableButton(button);
   }
 
   if (typeof(Page_ClientValidate) == 'function') 
   {
         // Force Page validation 
         Page_ClientValidate(validationGroup);                 
         
         // If validation passed
         if(Page_IsValid)
         {  
            DisableButton(button)       
         }
   }
   else
   {
        DisableButton(button);
   }
}


function DisableButton(button)
{   
    div1 = window.document.getElementById(button.id + 'Div1');
    div2 = window.document.getElementById(button.id + 'Div2');
    
    div1.style.display = "none";
    div2.style.display = "block";
}

 


This solution works with ASP.Net Ajax and with ASP.Net validators.
The final step is to create a Server Control... :)


References:


Understanding ASP.NET Validation Library


.

JavaScript Url Parser

Parsing the URL with JavaScript is a tedious task and can spend a lot of time.

A simple JavaScript library is the solution.

Poly9's Polyvalent JavaScript URL Parser is a complete URL parser that extracts the information from complex URLs:

http://user:password@WebServer.com/extension?argument1=value1#fragment

Get de JS File here.
The parser doesn't return the virtual directory.
A possible solution is to create a custom library and add the following functions:


// url format http://server/vdir/page.aspx?QueryStringParams
function GetVirtualDirectory(url) 
{ 
    var urlParts = url.split("/");     
    if (EndsWith(urlParts[3], ".aspx"))
    {
        return "";
    }
    
    return urlParts[3] + "/";    
} 
 


function EndsWith(str, end)
{
    var reg = new RegExp (end + "$");
    return reg.test(str);
}

04 March 2008

How to resolve JavaScript and CSS files path in master pages

JavaScript and css files path in master pages is a problem if the aspx pages are not in the same structure. For example, you may want some page on the site root (like default.aspx, login.aspx and logout.aspx) and others on a folder to organize the site.

 

The first attempt to solve this problem is use code blocks (<%= ... %>) with ResolveUrl, which give the following error:
The Controls collection cannot be modified because the control contains code blocks (i.e. <% … %>).


The second attempt is to use  <%# ... %>) and ResolveUrl, but nothing is returned to the browser.

 

The third attempt is to data bind the HtmlHead in code behind of the master page, since it derives from Control:

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    Page.Header.DataBind();
}

In the master page write: 



<style type="text/css"> 
  @import '<%# ResolveUrl("~/shared/css/style.css") %>'; 
  @import '<%# ResolveUrl("~/shared/css/grid.css") %>'; 
</style> 
<script type='text/javascript' src='<%# ResolveUrl ("~/shared/js/library.js") %>'></script>

The css problem can also be resolved with:



<head runat="server"> 
<link href="shared/css/style.css" rel="stylesheet" type="text/css" /> 
</head> 

The path is relative to the master page, and Asp.Net will solve the path based on the master page location.


The JavaScript files are still the problem. The third solution will fix it, or some code behind is in order!!!

A more elaborate solution would be to use resources and the WebResource.axd handler....

29 February 2008

How to insert a page break always in HTML

A common problem in HTML is how to insert a page break after an HTML element, to print a report for instance.

The solution is the page-break-after attribute defined as always.

Example:
Define the following style in the a CSS file or the HEAD HTML element:

<style> 
p { page-break-after: always } 
</style> 
In the body you can do the following: 


<div>:Insert a page break....</div> 
 
<p>This is a page break. </p> 

The text inside the <p> tag will appear in a new page.

28 February 2008

Multiple IE versions

In a test case scenario or for designers, multiple IE versions are needed for the testing environment.
The main problem is that only one version of IE can be installed.
To solve this problem use Multiple IE Versions.
More information here or download now.
The following IE Versions are supported:
- IE 3
- IE 4
- IE 5
- IE 5.5
- IE 6
- IE 7

Warning: This solution doesn't work on windows vista, at the time of this article.

28 January 2008

How To analyze T-SQL code?

Analyze T-SQL code using the following functions:

SET STATISTICS TIME ON 
-- query here 
SET STATISTICS TIME OFF 

In Management Studio Messages tab, you will see the number of milliseconds taken by each step in your query.

18 January 2008

IntelliSense not working with Linq

If intelliSense is not working with Linq and SingleOrDefault does not appear in the dataContext associated class, add a

using System.Linq;

:)

04 December 2007

WCF - The remote server returned an unexpected response: (400) Bad Request.

The WCF fault "The remote server returned an unexpected response: (400) Bad Request.", might be caused by some quota or timeout on server / client side.The solution is to increase reader quota values from binding configuration on both sides:

<bindings>
<wsHttpBinding>
    <binding name="WSHttpBinding_IService" closeTimeout="00:01:00" 
    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
    bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
    maxBufferPoolSize="2000000" maxReceivedMessageSize="2000000"
    messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
    allowCookies="false">
        <readerQuotas maxDepth="2000000" maxStringContentLength="2000000" maxArrayLength="2000000"
        maxBytesPerRead="2000000" maxNameTableCharCount="2000000" />
        <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" />
        <security mode="Message">
            <transport clientCredentialType="Windows" proxyCredentialType="None" realm="" />
            <message clientCredentialType="Windows" negotiateServiceCredential="true"
            algorithmSuite="Default" establishSecurityContext="true" />
        </security>
    </binding>
</wsHttpBinding>
</bindings>
<services>
    <service name="MyService" behaviorConfiguration="MyServiceTypeBehaviors">
        <endpoint address="" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService" contract="MyIService"/>
        <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex"/>
     </service>
</services>

30 November 2007