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.

SQL: Transaction count after EXECUTE indicates that a COMMIT or ROLLBACK TRAN is missing.

The following error message is got when the number of open transactions is different than the number of committed or rolled back transaction in the end of the stored procedure.

The global variable @@TRANCOUNT gives the number of opened transactions in the moment of check-up. If you are not sure what is number of opened transactions you can check the number at the end of the procedure and commit or rollback.

DECLARE @TranStarted bit
SET @TranStarted = 0

IF( @@TRANCOUNT = 0 )
BEGIN
BEGIN TRANSACTION
SET @TranStarted = 1
END
ELSE
SET @TranStarted = 0

-- do something
-- use select statements with locking rows or tables using
-- WITH ( UPDLOCK, HOLDLOCK ), WITH (HOLDLOCK)

IF( @@ERROR <> 0 )
GOTO Cleanup

--do something


IF( @@ERROR <> 0 )
GOTO Cleanup


-- if no errors commit the transaction
IF( @TranStarted = 1 )
BEGIN
SET @TranStarted = 0
COMMIT TRANSACTION
END

RETURN 1

-- in case of errors jump to the label cleanup to rollback the transaction
Cleanup:

IF( @TranStarted = 1 )
BEGIN
SET @TranStarted = 0
ROLLBACK TRANSACTION
END

RETURN 0

History support on Microsoft Ajax Library 3.5 SP1

The history control maintain the browser back button. An explanation of the feature is located in the Readme documentation of the Microsoft Ajax Library 3.5 SP1 package.
For quick reference the links are listed below:


In order to allow the browser history feature without using the server-side ScriptManager control, it is necessary to add the following markup into the page for Internet Explorer versions before 8:

<iframe id="__historyFrame" src="/System.Web.Extensions/3.5.0.0/3.5.30729.1/empty.htm" style="display:none;"></iframe>

C# Implicitly Typed Local Variables and Arrays

As a whole C# is a strongly-typed language. In other word the C# variables can hold explicitly defined data type.

From C# version 3.0 on the developer get the possibility to assign any values to a variable and the compiler to obtain accordingly the data type. It is not in the C# style as we know it but has some advantages of course.

var intVariable = 1235;
var stringVariable = "Hello";

The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement. The may be a built-in type, an anonymous type, a user-defined type, or a type defined in the .NET Framework class library.

The biggest advantage of this new feature is the usage in LINQ query expression using anonymous data types. The anonymous type name is automatically generated by the compiler and is not available at the source code level, but his usage saves much developer's efforts.

For more information in MSDN click here

How to get the value of the server variable LOGON_USER

1. Uncheck Allow Anonymous in the security tab of the site properties in IIS. At least Basic or Windows Authetication is needed.

2. Use the variable Request.ServerVariables("LOGON_USER") to get the full user name

How to open ComboBox (DropDown it) hosted in DataGridView with single mouse click.

The usage of ComboBox in a DataGridView delivers some limitations of its usage. Very common problem is opening the ComboBox with single click of the mouse. By default double mouse click is needed because the first click selects the cell and the second click enters into Edit mode where the ComboBox fires its DropDown event.

We can do this using DataGridView.CellClick event. The following code is enough to open the ComboBox and fire its DropDown event.


Private Sub DataGridView1_CellClick(ByVal sender As System.Object,
ByVal e As System.Windows.Forms.DataGridViewCellEventArgs)
Handles DataGridView1.CellClick
'enters into edit mode
DataGridView1.BeginEdit(True)

'checking if the editing control is a combobox
If TypeOf (DataGridView1.EditingControl) Is ComboBox Then

'casting the editing control and fire DropDown event
CType(DataGridView1.EditingControl, ComboBox).DroppedDown = True

End If
End Sub


DataGridView.EditingControl represents the control hosted by the current cell.