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.

Escape apostrophe in javascript and dynamic built scripts

The apostrophe in javascript is its string delimiter. To render the apostrophe on the response without errors it must be escaped using backslash \.

alert('John\'s name') will produce message box with text: John's name.

Using asp.net usually the scripts are built dynamically on server side before rendering the page. Remember that the backslash is also escape character in C# and you have to put two backslashes to build the javascript correctly:

Response.Write("alert('John\\'s name');");

FTP over SSL with IIS is not supported.

This is a common problem when you need more secure connection. Microsoft explains the features of their FTP server here:
http://support.microsoft.com/kb/283679

It is good to know that current FTP Service in IIS doesn't support Secure Sockets Layers (SSL). Of course that means your connection details and credentials to such service can be caught by Network listeners between you and the server. Therefore if you need secured connection you have to consider usage of Webdav over SSL or another FTP server which supports SSL.

A suggestion for free and easy to set up server is FileZilla FTP Server for Windows.

Edit shortcuts in Places bar in Save dialog / Open dialog in Windows

It's absolutely boring to navigate to your most often used folder in windows save or open dialogs. Th purpose of Places bar is to help you to do this faster. The Places bar locations can be edited via Group Policy editor in Windows XP Pro and Vista. Use the following way:

1. Open gpedit.msc (Start->Run)
2. Navigate to User Configuration -> Administrative Templates -> Windows Components -> Windows Explorer -> Common Open File Dialog
3. Open "Items displayed in Places bar" and write down the locations you want with their paths. Symbolic names are also allowed like Desktop.

SQL: How to check for existing contraint

Just an example how to get it form the database information schema:

IF NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA='dbo' AND CONSTRAINT_NAME='IX_Constraint' AND TABLE_NAME='TableName')
BEGIN
ALTER TABLE [dbo].[TableName] WITH CHECK ADD CONSTRAINT ..... /* constraints */
END

How to set column width in a CheckBoxList in an ASP.NET page

Maybe this is common problem since CheckBoxList control doesn't have set of parameters for obtaining column width and row height. But we always can use CSS for styling this control getting in mind he is rendered as html table or floated div tag.


<asp:checkboxlist runat="server" id="chkBoxList1" cssclass="chkBoxList" repeatcolumns="4" repeatlayout="Table">
</asp:checkboxlist>


Here we explicitly define the layout to be rendered as table (which is by default) and also need to define the css class "chkBoxList" in current page or web site theme.


<style>
.chkBoxList tr
{
height:24px;
}

.chkBoxList td
{
width:120px; /* or percent value: 25% */
}
</style>

Of course any other css styles can be attached here.

Only ASP.NET :)

SQL Stored Procedures - getting return value

Starting directly with example:

CREATE PROCEDURE ProcessValue
(
@value int,
@returnValue int OUTPUT
)
AS
BEGIN
/* do calculation and processing and assign the result value to output parameter */
SET @returnValue = value + 5*value

END

The following calling of the procedure shows how to get output parameter.
declare @result int
EXEC ProcessValue 15, @result OUTPUT


Of course this example is pretty simple - only for showing how to use. For such usage the SQL scalar-valued functions are better way.

Way for localizing MessageBox in Windows Forms

Very good article in code project, where you can see how the buttons of MessageBox can use custom text labels. The natural language of .NET platform will be overridden and only your labels will be shown.

http://www.codeproject.com/KB/miscctrl/Localizing_MessageBox.aspx

Actually if you use MessageBoxOptions in the parameters of MessageBox.Show(..) only the original labels are shown. But I don't think this is big problem.