IIS Url Rewriting - avoid repeat of querystring parameters

Using the URL rewriting mechanism of IIS causes repeat of querystring parameters on every postback, because it builds the postaback url (rewrites url) by appending the querystring to current url.

Actual url:
/product.aspx?type=hats

Rewritten url:
/product/hats

Rewritten url after postback:
/product/hats?type=hats
which is actually equal to /product.aspx?type=hats&type=hats
So the type value is "hats,hats".

To avoid repeat of querystring variables simply check if the url is already rewritten:

protected void Page_Load(object sender, EventArgs e)
{
if ( !String.IsNullOrEmpty(Request.ServerVariables["HTTP_X_ORIGINAL_URL"]) )
{
form1.Action = Request.ServerVariables["HTTP_X_ORIGINAL_URL"];
}
}

Detailed description:

SQL Server Express and IIS: Failed to generate a user instance of SQL Server due to failure in retrieving the user's local application data path.

SQL Express user instancing fails with the default IIS 7.x configuration. To solve this you can do the following:

1. Create new application pool in IIS
2. Open Application Pool Advanced settings
3. Change Identity from ApplicationPoolIdentity to NETWORK SERVICE and confirm
4. Change the application pool that the web application belongs to by opening Advanced setting of the web application

3 ways to get date in SQL without time

Here are 3 ways of getting date-only part of timestamp in SQL Server:

1. DATEADD( DAY, 0 , DATEDIFF(DAY,0, CURRENT_TIMESTAMP) )

2. CONVERT( datetime, FLOOR(CONVERT(float(24), GETDATE())) )

3. CAST( CONVERT(CHAR(8), GETDATE(),112) as DATETIME)

Strip time from javascript date object

Setting up the hours to zero does the trick:

var myDate = new Date(); //current date and time
myDate.setHours(0,0,0,0);

Passing Parameters to .NET Web Service as a Query String (GET Method) or POST Request

First of all the way of passing parameters must be defined in web.config as follows:

<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>


Then the URL of the web service may include parameters as query string.
http://tempuri.org/webservice.asmx/MethodCaseSensitive?parameter1=yes&parameter2=123

MethodCaseSensitive is the name of web method to be performed as part of the webservice called webservice.asmx.


In case you need POST method of sending parameters just use a form and text fields as in the following example:


<form name="input" action="http://tempuri.org/webservice.asmx/MethodCaseSensitive" method="post">
<input name="parameter1" type="text">
<input name="parameter2" type="text">
<input value="Submit" type="submit">
</form>

Both of methods return XML response as it is defined in the web method.

The Web Service results can be easily checked using the .NET ability for integrated passing of parametersin a web interface:
http://tempuri.org/webservice.asmx?op=MethodCaseSensitive

The screen allows the user to enter web service parameters and submit them. The result is the same.

ASP.NET Page Life Cycle, event order, master page, page and control events order


    PAGE: Page.OnPreInit()
        USER CONTROL: UserControl.OnInit()
MASTER PAGE: MasterPage.OnInit()
    PAGE: Page.OnInit()
    PAGE: Page.OnInitComplete()
    PAGE: Page.OnLoad()
MASTER PAGE: MasterPage.OnLoad()
        USER CONTROL: UserControl.OnLoad()
    PAGE: Page.OnLoadComplete()
           Page Event Handlers
    PAGE: Page.OnPreRender()
MASTER PAGE: MasterPage.OnPreRender()
        USER CONTROL: UserControl.OnPreRender()
    PAGE: Page.OnPreRenderComplete()
    PAGE: Page.OnSaveStateComplete()
        USER CONTROL: UserControl.OnUnload()
MASTER PAGE: MasterPage.OnUnload()
     PAGE: Page.OnUnload()

More information here:
ASP.NET Page Life Cycle

How to add custom shortcuts in Save / Open dialogs on Windows Vista

1. Start Group Policy Editor by starting gpedit.msc
2. Navigate to:
User Configuration -> Administrative Templates -> Windows Components -> Windows Explorer -> Common Open File Dialog
3. Open "Items displayed in Place Bar"
4. Enter appropriate paths for you shortcuts

The changes take effect immediately.

Stop a postback by javascript with IE7

Somehow the statement javascritpt:return false; doesnt work with IE 7. But there is a workaround by setting the event.returnValue to false.

OnClientClick="javascript:event.returnValue=false; return false;"

Minifying javascript source files.

I just want to recommend you a very simple tool called JSMin, which helps minifying the javascript sources. This code improvement significantly decreases the download time because of the smaller page size. The toll successfully removes whitespaces and comments which are not needed on client side.

The tool is available as a script or a console application.

The usage of jsmin.exe is simple:
jsmin.exe output.js

Javascript Query String

The query string is reachable through window.location.search property. Splitting it by & gives you list of passed GET parameters.


function GetPageParameter(param) {
var query ='';
if (window.location.search.length>3){
//removes '?' from the query string
query = window.location.search.substring(1);
}else{
return '';
}
params = query.split("&");
for (i=0;i1){
if (pair[0] == param) {
return pair[1];
}
}else{
return '';
}
}
return '';
}

var value = GetPageParameter("value");

How to fix a WebClient timeout issue

The issue occurs when the time for generating the whole response of a WebClient request is longer than the default timeout (2 minutes / 60000 miliseconds) . So the solution is to increase this timout value. The WebClient class doesn't have such property or method, so you have 2 possibilities:

1. Use HttpWebRequest instead of WebClient and set its timeout by ReadWriteTimeout property. Of course the usage of this class is more complex than WebClisnt's one but it gives you more flexibility.

2. Make a derived class (wrapper) , which willset the timeout propery of the base class of the WebClient.


public class MyWebClient: WebClient
{
//time in milliseconds
private int timeout;
public int Timeout
{
get {
return timeout;
}
set {
timeout = value;
}
}

public
MyWebClient()
{
this.
timeout = 60000;
}


public MyWebClient(int timeout)
{
this.
timeout = timeout;
}

protected override WebRequest GetWebRequest(Uri address)
{
var result = base.GetWebRequest(address);
result
.Timeout = this.timeout;
return result;
}
}



The usage is pretty much the same as the WebClient's usage but we have to specify the new timeout in the constructor or by setting the Timeout property:

MyWebClient wClient = new MyWebClient(1800000);

UTF8Encoding objUTF8 = new UTF8Encoding();

try
{
byte[] data =
wClient.DownloadData(url);

File.WriteAllBytes(
System.AppDomain.CurrentDomain.BaseDirectory + @"\files\output.xls", data);

wClient = null;
objUTF8 = null;
}
catch (Exception ex)
{
objWebClient = null;
objUTF8 = null;

}

As you see this timeout property solves the problems by client side. The server response should also have longer timeout for generating the response. It is set by machine.config or web.config - httpRuntime section. Note that the timeout in web.config is specified in seconds.

SQL – Cannot resolve collation conflict for equal to operation

When the sql collation of strings is not equal but need to me compared we need to explicitly define the collation. The most common way is the using of the default database collation as in the example:

WHERE Table1.Name COLLATE DATABASE_DEFAULT=Table2.Name COLLATE DATABASE_DEFAULT
The collation change can be performed on tables joining, 'where' clausesq as part of stored procedures and functions, as well as database Default collation change.

Forcing downloading files by save dialog

Here is the code snippet for downloading files with asp.net:

Response.Clear();

Response.AddHeader("content-disposition", "attachment;filename=" + filename);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "image/jpeg";

byte[] data = System.IO.File.ReadAllBytes(MapPath(url));
Response.BinaryWrite(data);
Response.Flush();
Response.End();


The key moment in forced save dialog is the header "content-disposition" with file attachment. This will tell to your browser to show you dialog and give you the possibility to get directly that file.
If you use attachment in "inline" header (appending it instead of "content-disposition") the file is gonna be opened in the same window. Browser back button can get you back on your page.

List of content types can be found here: MIME Reference

Visual Studio - Pre or Post-build events - copying example

The Pre or Post events are simple and useful actions before or after building the solution, which can be used for performing customized actions to simplify deployment or testing.

The following example copying all output files to myproject\bin located in the solution directory.
Ex.
copy "$(TargetDir)*.*" "$(SolutionDir)myproject\Bin"

For reference see Macro table in MSDN

Batch files can be used as well for more complex predefined actions using the call statement Ex. call C:\Batch.bat

VB.NET How to encrypt and decrypt a string (password) using Rijndael cipher.

The Rijndael algorithm is part of AES (Advanced encryption standard) which is approved by US government as enough secure way of protecting data.

The .NET offers pretty easy way for encrypting and decrypting data using Rijndael cipher:

Dim cryptography As New System.Security.Cryptography.RijndaelManaged
Dim ms As New MemoryStream()
Dim cs As New CryptoStream(ms, _
cryptography.CreateEncryptor(ASCIIEncoding.ASCII.GetBytes("[16 bytes ascii string]"), _
ASCIIEncoding.ASCII.GetBytes([16 bytes ascii string])), CryptoStreamMode.Write)
Dim sw As New StreamWriter(cs)
sw.Write(inputString)
sw.Flush()
cs.FlushFinalBlock()
ms.Flush()
Dim encryptedString As String = _
Convert.ToBase64String(ms.GetBuffer(), 0, CType(ms.Length, Integer))

The example encrypts inputString using for private key and salt two 16 bytes ascii strings. The private key and salt can be predefined as byte arrays . The result is 128 bit encrypted string stored in encryptedString.


Dim cryptography As New System.Security.Cryptography.RijndaelManaged
Dim buf As Byte() = Convert.FromBase64String(encryptedString.Trim())
Dim ms As New MemoryStream(buf)
ms.Position = 0
Dim cs As New CryptoStream(ms, _
cryptography.CreateDecryptor(ASCIIEncoding.ASCII.GetBytes("[16 bytes ascii string]"), _
ASCIIEncoding.ASCII.GetBytes("[16 bytes ascii string]")), _
CryptoStreamMode.Read)
Dim sr As New StreamReader(cs)
Dim decryptedString As String = sr.ReadToEnd()

The encrypted string is decrypted using the same private key and salt as in the encrytpion in and it is stored in
decryptedString finally.