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

14 March 2007

Visual Studio 2005 Code Snippets

IntelliSense Code Snippets are reusable, task-oriented blocks of code. Visual Studio 2005 has some code snippets. There are some additional Code Snippets

Download, install and enjoy.

10 January 2007

Visual Studio 2005 SP1, dotnetfx 3.0, LINQ => Refactoring gone

I installed Visual Studo 2005 SP1, dotnet 3.0, Visual Studio Code Name "Orcas" and LINQ.
When I wanted to use the refactoring the SmartTags stopped working and the Refactor option was missing!!!
I needed to refactor some .net 2.0 code and even nothing.
So I went googling and found the solution here!!!
Only the last option worked for me :)

The steps are:
1) Launch regedit.exe
Open HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\8.0\Packages\{A066E284-DCAB-11D2-B551-00C04F68D4DB}\SatelliteDLL
Edit the "Path" value and change it from "C:\Program Files\Microsoft Visual Studio 8\VC#\VCSPackages\1033\" to "C:\Program Files\Microsoft Visual Studio 8\VC#\VCSPackages\"
Restart Visual Studio and see if these problems are fixed?

2) Open a command prompt, go to
C:\Program Files\Microsoft Visual Studio 8\Common7\IDE
Run
(i) devenv /setup
(ii) devenv /resetuserdata
(iii) devenv /resetsettings CSharp

When installing orcas / LINQ, be afraid, be very afraid.

02 January 2007

How to Pad Left a number?

Padding left a number using SQL Server is implemented using the REPLICATE TSQL function.
Here is an example to format a date:
DECLARE @Date VARCHAR(8)
SET @Date = CAST(YEAR(GETDATE()) AS VARCHAR(4))
SET @Date = @Date + REPLICATE('0', 2 - DATALENGTH(CAST(MONTH(GETDATE()) as VARCHAR))) + CAST(MONTH(GETDATE()) as VARCHAR) 
SET @Date = @Date + REPLICATE('0', 2 - DATALENGTH(CAST(DAY(GETDATE()) as VARCHAR))) + CAST(DAY(GETDATE()) as VARCHAR) 
SELECT @Date


Create a SQL Server function for padleft and padright and you job will be simplefied. Here is a good place to start.

18 December 2006

Visual Studo 2005 SP1 is here

Today I tried to install Visual Studo 2005 SP1 and had some setup issues.
I hope this guide will help you as a reference of what to do:
1) Remove SP beta - Activate show updates in add-remove programs.
Don't forget to have your original VS.Net installation medium available!!!
2) Unistall the Web Application Project, since it is built-in to SP1
3) The following error is normal:
The installation of C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\ZNW442\VS80sp1-KB926601-X86-ENU.msp is not permitted due to an error in software restriction policy processing. The object cannot be trusted.
A workaround:
i) Open Administrative Tools
ii) Open Local Security Policy
iii) Select Software Restriction Policies
iv) If no software restrictions are defined, right click the Software Restriction Policies node and select New Software Restriction Policy
v) Double click Enforcement and select "All users except local administrators"
vi) Click OK
vii) Reboot the machine

More information on Heath Stewart's Blog
To learn more about Visual Studio SP1 visit Development Catharsis

Unobtrusive Flash Objects (UFO)

Unobtrusive Flash Objects (UFO) is a DOM script that embeds the Flash object and resolves the flash activation problem.
UFO is free and supports the W3C standards.

Example:

<html>
<head>
<script src="ufo.js" type="text/javascript"></script>
<script type="text/javascript">
var FO = { movie:"FlashMovie.swf", width:"200", height:"100",
majorversion:"6", build:"40" };
UFO.create(FO, "FlashLayer");
</script>
</head>
<body>
<div id="FlashLayer">
<p>Alternate Content


</div>
</body>
</html>

More information and dowload here.

How to place flash on back of HTML?

To place flash on back of HTML, set the flash container with z-index to -1:
<div id="flashContent" style="z-index:-1" ></div>

and set flash variable wmode to opaque.